var plp = ''; //当前聊天对象
var memberImage = [];
var payChanel = null;
var paycode = null;
var ChatID = "";
var pageFun = {
	//定位
	GPS: function() {
		var ace = fun.getCache('ace');
//		if(!ace || ace == false){
			mui.plusReady(function(){
				plus.geolocation.getCurrentPosition( function ( p ) {
					fun.setCache("lng",p.coords.longitude);
					fun.setCache("lat",p.coords.latitude);
					fun.setCache("ace",p.address.district);
					fun.setCache("city",p.address.city); 
					$(".position1 b:first").text(p.address.district);
					$(".position1").attr("lng", p.coords.longitude).attr("lat",p.coords.latitude);
					pageFun.indexshow();
					pageFun.homebottomlist();
				}, function ( e ) {
					mui.toast('定位失败，请手动选择区域');
					$('.position1').trigger('tap');

				});
			});
//		}else{
//			
//		}
	},
	
	//用地址换经纬度
	getPlace: function(id,addr,city){
		plus.maps.Map.geocode(addr,{city:city},function(event){
			var address = event.address;  // 转换后的地理位置
			var point = event.coord;  // 转换后的坐标信息
			var coordType = event.coordType;	// 转换后的坐标系类型
			$(id).attr("lng", point.longitude);
			$(id).attr("lat", point.latitude);
			var lng = fun.getCache("lng");
			var lat = fun.getCache('lat');
			if(lng == '' && lat == "" || lng == null && lat == null){
				fun.setCache("lng",point.longitude);
				fun.setCache("lat",point.latitude);
			}
			pageFun.indexshow();
		},function(e){
//			alert\n("Failed:"+JSON.stringify(e));
		});
	},
	isNetWorkState:function(){
		function plusReady() {
			var types = {};
			types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown connection";
			types[plus.networkinfo.CONNECTION_NONE] = "None connection";
			types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet connection";
			types[plus.networkinfo.CONNECTION_WIFI] = "WiFi connection";
			types[plus.networkinfo.CONNECTION_CELL2G] = "Cellular 2G connection";
			types[plus.networkinfo.CONNECTION_CELL3G] = "Cellular 3G connection";
			types[plus.networkinfo.CONNECTION_CELL4G] = "Cellular 4G connection";
			alert("Network: " + types[plus.networkinfo.getCurrentType()]);
		}
	},
	initPage:function(){
		mui.plusReady(function() {
			var gt = plus.push.getClientInfo();
			fun.setCache("cid",gt.clientid);
			plus.push.addEventListener( "click",function (msg) {
			// 分析msg.payload处理业务逻辑 
			}, false ); 
			var network = plus.networkinfo.getCurrentType();
			if(network != 1){
				pageFun.version();
				pageFun.GPS();				
			}
		});
		fun.bindLinkToRouter('#tabBar a,.footer9 a,rgba,.Set_Up *');
		
		document.documentElement.style.webkitUserSelect='none';
		document.documentElement.style.webkitTouchCallout = "none"; 
	
		InitWebIM();
		var android_ios = navigator.userAgent;
		var isAndroid = android_ios.indexOf('Android') > -1 || android_ios.indexOf('Adr') > -1; //android终端
		var isiOS = !!android_ios.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if(isAndroid == true){
		}else if(isiOS == true){
			$("head").append("<link>");
			css = $("head").children(":last");
			css.attr({
			    rel: "stylesheet",
			    type: "text/css",
			    href: "css/iosstyle.css"
			});
		}
		$(".sPage").css("height",$(window).innerHeight()+'px');
		if(!localStorage.C){
			$("#tpl_YD").show();
			pageFun.YD();
		}else{
			$(".YD").remove(); 
		}
		if(!localStorage.token){
			$("#Land_header h2");
//			$("#Land_height").hide();
			pageFun.reg();
//			$("#tpl_Land").addClass('popPageShow');
			$(".footer0").hide();
			$("#Land_height").css("height",$(window).innerHeight()+'px');
			$("#tpl_Land").css("height",$(window).innerHeight()+'px');
			pageFun.login();
		}else{
//			$("#tpl_Land").removeClass('popPageShow');
			pageFun.hxLogin();
		}
		
	},
	//用经纬度换位置
	indexgps: function(){
		var lng = fun.getCache("lng");
		var lat = fun.getCache("lat");
		var usergps = new BMap.Point(lng, lat);
		var geoc = new BMap.Geocoder();
		geoc.getLocation(usergps, function(rs) {
			var addComp = rs.addressComponents;
			$(".position1 b:first").text(addComp.district);
			fun.setCache("ace",addComp.district);
			fun.setCache("city",addComp.city);
			$(".position1").attr("lng", lng).attr("lat", lat);
			pageFun.indexshow();
		});
	},
	//生成地图
	gpsmap: function(){
		var parm = viewApi.parms;
		var lng = parm[0];
		var lat = parm[1];
		$('#content_map').empty();
		var html='<div id="newmap" style="width: 100%;  position: absolute;"></div>';
		$('#content_map').html(html);			
		mui.plusReady(function() {
			var lngmy=fun.getCache("lng");
			var latmy=fun.getCache("lat");
			var district = fun.getCache("city");
			var em=null,map=null;
			var myPoint=new plus.maps.Point(lngmy,latmy);
			var youPoint=new plus.maps.Point(lng,lat);
			$('#newmap').height(document.documentElement.clientHeight);
			
			map = new plus.maps.Map("newmap");
			map.centerAndZoom(youPoint,15);
			map.show();
			
			
			map.showUserLocation( true );
			var marker=new plus.maps.Marker(youPoint);
			marker.setIcon("/images/map.png");
			map.addOverlay(marker);
			var  searchObj = new plus.maps.Search( map );
			searchObj.onRouteSearchComplete = function ( state, result ) {
				if ( state == 0 ) {
					if ( result.routeNumber <= 0 ) {
						alert( "没有检索到结果" );
					}
					for(var i=0; i<result.routeNumber; i++){
						map.addOverlay( result.getRoute( i ) );
					}
				} else {
					alert( "检索失败" );
				}
			}
			
			$(".icon-gongjiao").unbind('tap').on('tap',function(){
				map.clearOverlays();
				searchObj.transitSearch(myPoint,youPoint,district);
				
			})
			$(".icon-jiache").unbind('tap').on('tap',function(){
				map.clearOverlays();
				searchObj.drivingSearch(myPoint,"",youPoint,"" );
			})
			$(".icon-buxing").unbind('tap').on('tap',function(){
				map.clearOverlays();
				searchObj.walkingSearch(myPoint,"",youPoint,district);
			})
			fun.bindOnce(".icon-zuojiantou",'tap',function(){
				map.reset();
				map.resize();
				map.hide();
				viewApi.back();
			});
			(function(M){
				var oldBack = M.back;
				M.back = function() {
					map.reset();
					map.resize();
					map.hide();
					viewApi.back();
				};
			})(mui);
		});	
	},
	//计算距离
	getdistance: function() {
		var lngmy=fun.getCache("lng");
		var latmy=fun.getCache("lat");
		var map = new BMap.Map();
		var pointA = new BMap.Point(Number(lngmy),Number(latmy));
		$(".home-list li").each(function(){
			var lngyou=$(this).find(".lxr_gps").attr("lng");
			var latyou=$(this).find(".lxr_gps").attr("lat");
			var pointB = new BMap.Point(Number(lngyou),Number(latyou));
			var distance= map.getDistance(pointA,pointB);
			if(distance>=1000){
				$(this).find(".lxr_gps").text((distance/1000).toFixed(2)+"km");
			}else{
						
				$(this).find(".lxr_gps").text(distance.toFixed(2)+"m");
			}
		})
	},
	tpl_ProductPage2:function(title,content,img,parm){
		var to = fun.getCache('token');
		
		var Intent = null,
            File = null,
            Uri = null,
            main = null;
        var shares = null;
        var shareImageUrl = '';
        mui.plusReady(function() {  
            updateSerivces();
            if (plus.os.name == "Android") {
                Intent = plus.android.importClass("android.content.Intent");
                File = plus.android.importClass("java.io.File");
                Uri = plus.android.importClass("android.net.Uri");
                main = plus.android.runtimeMainActivity();
            }
        });
		function updateSerivces() {
            plus.share.getServices(function(s) {
                shares = {};
                for (var i in s) {
                    var t = s[i];
                    shares[t.id] = t;
                }
            }, function(e) {
                mui.toast("获取分享服务列表失败：" + e.message);
            });
        }
        /**
         * 分享操作
         */
        function shareAction(id, ex) {
            var s = null;
            if (!id || !(s = shares[id])) {
//              console.log("无效的分享服务！");
                return;
            }
            if (s.authenticated) {
//              console.log("---已授权---");
                shareMessage(s, ex);
            } else {
//              console.log("---未授权---");
                s.authorize(function() {
                    shareMessage(s, ex);
                }, function(e) {
//                  console.log("认证授权失败");
                });
            }
        }
        /**
         * 发送分享消息
         */
        function shareMessage(s, ex) {
            var msg = {
                href: 'http://www.yuzhuli.com/Share/index.html?id='+parm+'&token='+to,
                title: title,
                content: content,
                thumbs: [img],
//	                pictures: ['http://img3.3lian.com/2013/v10/4/87.jpg'],
                extra: {
                    scene: ex
                }
            };
            s.send(msg, function() {
                console.log("分享成功!");
            }, function(e) {
                console.log("分享失败!");
            });
        }
        /**
         * 分享按钮点击事件
         */
        function shareHref() {
            var ids = [{
                    id: "weixin", 
                    ex: "WXSceneSession"  /*微信好友*/
                }, {
                    id: "weixin",
                    ex: "WXSceneTimeline" /*微信朋友圈*/
                }],
                bts = [{
                    title: "发送给微信好友"
                }, {
                    title: "分享到微信朋友圈"
                }];
            	plus.nativeUI.actionSheet({
                    cancel: "取消",
                    buttons: bts
                },
                function(e) {
                    var i = e.index;
                    if (i > 0) {
                        shareAction(ids[i - 1].id, ids[i - 1].ex);
                    }
                }
            );
        }
        $('.SignShareBtn').unbind('tap').on('tap',function(){
        	shareHref();
        });
	},
	// 评论
	Comment: function() {
		var parm = viewApi.parms;
		plp = parm[0];
		$("html,body,.mypage,.container,#Comment_id").css("height", "100%");
		$("#Comment_id").css("background-color", "#fff");
		$(".icon-wujiaoxing").css("color", "#ff9d09");
		var Comment_xx = 5;
		$(".Comment-xx span").unbind('tap').on('tap',function() {
			$(".icon-wujiaoxing").css("color", "#eee");
			Comment_xx = $(this).attr("xx");
			$(".icon-wujiaoxing").slice(0, Comment_xx).css("color", "#ff9d09");
		});
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ')" imgdata=' + res.target.result + '><span class="remove">删除</span></li>');
				$(".remove").unbind('tap').on('tap',function() {
					$(this).parents(".tu").remove();
				});
			}
			fr.readAsDataURL(file);
		});
		$("#Comment-btn").unbind('tap').on('tap',function() {
			var content2 = $(".C-content textarea").val();
			var img2 = "";
			$(".S_T_D").find(".tu").each(function(i) {
				var listimg2 = $(".S_T_D").find(".tu").eq(i).attr("imgdata");
				img2 += "@" + listimg2;
			});
			img2 = img2.substr(1);
			if(img2 == '@@@'){
				img2 = '';
			}
			Api.post(Api.shop_ping,{xing:Comment_xx,content:content2,id:plp,img:img2},function(obj){
				if(obj.s){
					viewApi.back();
				} else {
					fun.tan("评论失败");
				}
			});
		});
	},
	// 商品评论
	Comment2: function() {
		var parm = viewApi.parms;
		plp = parm[0];
		var pop = plp.split("_");
		$("html,body,.mypage,.container,#Comment_id").css("height", "100%");
		$("#Comment_id").css("background-color", "#fff");
		$("#Comment2").height($(window).height()-$('.header_1').height()).addClass('scroll');
		var orderCode = pop.shift();
		$("#Comment2").empty();
		var u = "";
		u += '<button class="btn" id="Comment-btn">确认</button><div class="clearfix" style="display: none;"></div>'
		$.each(pop, function(i,d) { 
			u += '<div class="proItem" shop_id="'+d+'" ><div class="clearfix" style="display: none;"></div><div class="C-content" shop_id="'+d+'" Order="'+orderCode+'"><textarea name="" placeholder="请填写您的评价" class="C-textarea"></textarea></div><ul class="S_T_D S_T_D_'+i+' clearfix"><li>上传图片</li><li class="add fileuploadBtn" did="Comment'+i+'"><span  class="iconfont icon-tianjiadizhi" style="position: relative;"><input type="file" id="Comment'+i+'" class="upfile"/></span></li></ul></div>';
		});
		$("#Comment2").html(u); 
		
		var jg = '<div style="width: 100%;height: 0.76rem;visibility: hidden;"></div>';
		$(".Comment-main").append(jg);
		
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ')" imgdata=' + res.target.result + '><span class="remove">删除</span></li>');
				$(".remove").unbind('tap').on('tap',function() {
					$(this).parents(".tu").remove();
				});
			}
			fr.readAsDataURL(file);
		});
		var this_off = true;
		$("#Comment-btn").unbind('tap').on('tap',function() {
			if(this_off == true){
				this_off = false;
				var lydata = [];
				$.each($(".proItem"),function(ii,dd){
					var images = [];
					$.each($(this).find('.tu'),function(i,d){
						images.push($(d).attr('imgdata'));
					});
					lydata.push({
						pro_id:$(dd).attr('shop_id'),
						images:images,
						content:$(this).find('.C-content textarea').val()
					}); 
				});
				var data = { order_id:orderCode,lydata:lydata };
				Api.post(Api.product_ping,data,function(obj){
					if(obj.s){
						viewApi.back();
						this_off = true;
					} else {
						this_off = true;
						fun.tan("评论失败");
					}
				});
			}else{
				fun.tan("请勿重复提交");
			}
		});
	},
	//	店铺详情
	shop: function(){
		$(".btn").unbind('tap').on('tap',function() {
			$(".Eject,.rgba").show();
		});
		$("head").append("<link>");
		css = $("head").children(":last");
		css.attr({
		    rel: "stylesheet",
		    type: "text/css",
		    href: "css/mui/mui.picker.min.css"
		});

		$('#demo1').unbind('tap').on('click',function(){
			var optionsJson = this.getAttribute('data-options') || '{}';
			var options = JSON.parse(optionsJson);
			var id = this.getAttribute('id');
			var picker = new mui.DtPicker(options);
			var this_ = this;
			var len = $('.mui-dtpicker').length;
			picker.show(function(rs) {
//						var data = rs.value;
				this_.innerText = rs.text;
				picker.dispose();
			});
			if(len>=1){
				var len2 = len-1;
				for(var i = 0 ; i < len2;i++){
					$('.mui-dtpicker').eq(i).remove();
					$('.mui-backdrop').eq(i).remove();
				}
				return false;
			}
		});
		$('#demo3').unbind('tap').on('click',function(){
			var optionsJson = this.getAttribute('data-options') || '{}';
			var options = JSON.parse(optionsJson);
			var id = this.getAttribute('id');
			var picker = new mui.DtPicker(options);
			var this_ = this;
			var len = $('.mui-dtpicker').length;
			picker.show(function(rs) {
//						var data = rs.value;
				this_.innerText = rs.text;
				picker.dispose();
			});
			if(len>=1){
				var len2 = len-1;
				for(var i = 0 ; i < len2;i++){
					$('.mui-dtpicker').eq(i).remove();
					$('.mui-backdrop').eq(i).remove();
				}
				return false;
			}
		});
		
		$(".rgba").unbind('tap').on('tap',function() {
			$(".Eject,.rgba").hide();
		});
		$("header").css("z-index","55");
		var parm = viewApi.parms;
		plp = parm[0];
	    Api.post(Api.shop_info,{id:plp},function(obj){
	    	if(obj.s){
				$(".icon-wujiaoxing").css("color","#eee");
	    		var p = obj.d;
	    		var lun = p.pinglun_info;
	    		$("#pl").find('.block2').remove();
    			if(p.id == plp){
    				$(".left .name,#E_name").text(p.shopname);
    				if(p.tel==null){
    					$(".phone a").attr("href","tel:"+p.phone);
    				}else{
    					$(".phone a").attr("href","tel:"+p.tel);
    				}
    				$("#content_pre").html(p.ds);
    				$(".ShopAddress").attr('lng',p.lng).attr('lat',p.lat);
//  				$(".left .XL").text("已订" + p.order_num);
    				$(".list-header img").attr("src",p.listimg);
    				$(".list-header .ShopAddress span:nth-last-child(1)").text(p.pro + p.city + p.area + p.addr);
    				$("#shop_score span").slice(0,p.xing).css("color","#ff9d09");
    				
  					pageFun.initLBT('ShopSwiperBanner',p.showimg);
  					
		    		$.each(lun, function(ii,dd) {
		    			var name = dd.nickname != null?dd.nickname:'用户';
		    			var tpl = '<div class="block2 clearfix"><div class="left"><p class="">'+name+'</p>';
		    			tpl += '<p class="score clearfix"><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span></p>';
			    		tpl += '<p>'+dd.content+'</p>';
		    			tpl += '</div>';
		    			tpl += '<p class="fl-left"><span style="letter-spacing: 0.02rem;">'+dd.ctime+'</span></p>';
		    			if(dd.ping_img && dd.ping_img.length>0){
			    			tpl += '<p class="fl-left img" style="">';
			    			$.each(dd.ping_img,function(iii,ddd){
			    				if(ddd == ""){
			    					
			    				}else{
				    				tpl += '<i style="background-image:url('+ddd+')"></i>';
			    				}
			    			});
			    			tpl += '</p>';
		    			}
		    			tpl += '</div>';
		    			$("#pl").append(tpl);
		    			$(".block2").eq(ii).find(".icon-wujiaoxing").slice(0,dd.xing).css("color","#ff9d09");
		    		});
//	    			pageFun.LBT('#shopBanner','.shopSwriper');
	    			$(".ShopAddress").unbind('tap').on('tap',function(){
	    				var lng=$(this).attr('lng');
	    				var lat=$(this).attr('lat');
	    				viewApi.go("#tpl_gpsmap",[lng,lat]);
	    			})
    			}
	    	}else{
	    		fun.tan("获取失败");
	    	}
	    });
		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
	    $("#lj-yy").unbind('tap').on('tap',function(){
	    	var num = $("#lj-num").val();
	    	var time1 = $("#demo1").text();
	    	var time2 = $("#demo3").text();
	    	var phone = $("#lj-phone").val();
	    	var address2 = $(".ShopAddress span:nth-last-child(1)").text();
			var time = time1 + "-"+ time2;
			var token = fun.getCache('token');
			if(token){
		    	if(num && time && phone){
		    		if(Z_phone.test(phone)){
					    Api.post(Api.shop_order,{person_num:num,order_time:time,phone:phone,address:address2,shopid:plp},function(obj){
					    	if(obj.s){
					    		fun.tan("预约成功");
					    		$(".Eject ,.rgba").hide();
					    	}else{
					    		fun.tan("预约失败");
					    	}
					    });
		    		}else{
		    			fun.tan("请填写正确手机号");
		    		}
		    	}else{
		    		fun.tan("请填写完整信息");
		    	}
			}else{
				fun.tan('请先登录');
			}
	    	
	    })
	},
	//	维修预约
	tpl_RepairListInfo: function(){
		var parm = viewApi.parms;
		var starindex = 0;
		var hm = $(window).height() - $('.DetailsInfo').height() -$('.DetailsInfo').height() - $('.pHead.header_1').height();
		
		$('.pBody.RepairInfo').height(hm).css({'overflow-y':'scroll','-webkit-overflow-scrolling':'touch'});
		
		$('.icon-pingjia').unbind('tap').on('tap',function(){
			$('.popComment').fadeIn(function(){
				closePop();
				star();
			});
		});
		
		function star(){
			$('.popCommentMain .score span').unbind('tap').on('tap',function(){
				$('.popCommentMain .score span').css('color','#eee');
				starindex = $(this).index();
				starindex++;
				$('.popCommentMain .score span').slice(0,starindex).css("color","#ff9d09");
			})
		}
		
		function closePop(){
			var dom = $('.popComment');
			dom.find('.icon-cha').unbind('tap').on('tap',function(){
				dom.fadeOut();
			});
		}
		
		//   *************** 获取数据  ******************
		function getComment(){
			Api.post(Api.maintainer_info,{id:parm[0]},function(obj){
				if(obj.s){
					var obj = obj.d;
					$('.RepairInfo')
					$('.ContentMain .info .name').text(obj.name);
					$('.HeadImg img').attr('src',obj.img);
					$('.ContentMain .info .phone').text(obj.mobile);
					$('.ContentMain .content').text(obj.assessment != ''?obj.assessment:'暂无介绍' );
					$('.ContentMain .address').text(obj.address);
					$('.DetailsInfo p').eq(0).text(obj.address);
					$('.DetailsInfo p').eq(1).text(obj.mobile);
					$('.RepairListInfoBtn a').attr('href','tel:'+obj.mobile);
					var html = '';
					$.each(obj.comments,function(i,d){
						html += '<li><p><span>'+d.nickname+'</span><span>'+d.time+'</span></p><p>'+d.content+'</p></li>';
					});
					$('.RepairComment ul').html(html);
				}else{
					mui.toast(obj.m);
				}
			});
		}
		getComment();
		
		// 维修评论
	    $("#popCommentBtn").unbind('tap').on('tap',function(){
	    	var content = $('.popCommentMain textarea').val();
			var token = fun.getCache('token');
			if(token){
				if(content){
				    Api.post(Api.add_comment,{type:'maintainer',id:parm[0],content:content,score:starindex},function(obj){
				    	if(obj.s){
				    		fun.tan("评论成功");
							getComment();
				    		$('.popComment').fadeOut();
				    	}else{
				    		fun.tan("评论失败");
				    	}
				    });
				}else{
					mui.toast('内容不能为空')
				}
			}else{
				fun.tan('请先登录');
			}
	    });
	},
	
	tpl_PopApply:function(){
		pageFun.newupphoto('#PopApplyUpBtn');
		
		$('#timebtn').unbind('tap').on('tap',function(){
			var optionsJson = this.getAttribute('data-options') || '{}';
			var options = JSON.parse(optionsJson);
			var picker = new mui.DtPicker(options);
			picker.show(function(rs) {
				$('#timebtn').parent().find('input').val(rs.text);
				picker.dispose();
			});
		});
		
		$('.PopApplyBtn').unbind('tap').on('tap',function(){
			var dom = $('.InputsBox li');
			var name = dom.eq(0).find('input').val();
			var photo = dom.eq(1).find('input').val();
			var address = dom.eq(2).find('input').val();
			var shop_name = dom.eq(3).find('input').val();
			var time = dom.eq(4).find('input').val();
			var imgs = '';
			$.each($('.addimg .tu'),function(i,d){
				imgs += $(d).find('i').attr('src') + '@';
			});
			imgs = imgs.substr(0, imgs.length - 1);
			
			if(name && photo && shop_name && imgs && time){
				Api.post(Api.apply_free_play_mj,{free_date:time,mobile:photo,applicant_name:name,address:address,card_room:shop_name,business_license:imgs},function(obj){
					if(obj.s){
						mui.toast('申请成功');
						viewApi.go('#tpl_My');
					}else{
						mui.toast(obj.m);
					}
				});

			}else{
				mui.toast('请输入完整信息')
			}
		});
		


	},
	gettime2:function(){
		var currYear = (new Date()).getFullYear();	
		var opt={};
		opt.date = {preset : 'date'};
		opt.datetime = {preset : 'datetime'};
		opt.time = {preset : 'time'};
		opt.default = {
			theme: 'android-ics light', //皮肤样式
	        display: 'modal', //显示方式 
	        mode: 'scroller', //日期选择模式
			dateFormat: 'yyyy-mm-dd',
			lang: 'zh',
			showNow: true,
			nowText: "今天",
	        startYear: currYear - 10, //开始年份
	        endYear: currYear + 10 //结束年份
		};
	  	$("#appDate").mobiscroll($.extend(opt['date'], opt['default']));
	  	var optDateTime = $.extend(opt['datetime'], opt['default']);
	  	var optTime = $.extend(opt['time'], opt['default']);
	    $("#lj-time").mobiscroll(optDateTime).datetime(optDateTime);
	    $("#lj-time2").mobiscroll(optDateTime).datetime(optDateTime);
	    $("#appTime").mobiscroll(optTime).time(optTime);
	},
	//获取列表信息
	Get_Chessandcardroom:function(data,Key,ace){
		var lng = fun.getCache("lng");
		var lat = fun.getCache("lat");
		Api.post(Api.shop_list,{ace:ace,lng:lng,lat:lat,type:data,key:Key},function(obj){
			if(obj.s){
				var p = obj.d;
				$("#brandUL").empty();
				var y = "";
				//is_discount_today
				$.each(p, function(i,d) {
					y += '<li class="clearfix" num="'+d.xing+'"><a href="#/tpl_shop/' + p[i].id + '"><img src="' + p[i].listimg + '" /><div><p class="shop_name">' + p[i].shopname + '</p><p class="score"><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span></p>';
					
					y += '<p><span>' + p[i].area + '</span>';
					
					if(d.is_discount_today == 1){
						y += '<span class="jinri">今日优惠</span>';						
					};
					
					y += '<span class="lxr_gps" lng="' + p[i].lng+ '" lat="'+ p[i].lat+'">...</span></p></div></a></li>';
				});
				$("#brandUL").append(y);
				$("#brandUL li").each(function(i,d){
					var xing = $(this).attr("num");
					$(this).find(".score span").slice(0,xing).css("color","#ff9d09");						
				})
				pageFun.getdistance();
			} else {
				fun.tan("获取失败");
			}
		});
	},
	//	棋牌室列表
	brand: function() {
		var BrandPosition = fun.getCache('ace');
		if(BrandPosition){
			$("#currentPosition").html('当前位置：'+fun.getCache('ace'));
		}else{
			$("#currentPosition").html('当前位置：定位失败');
		}
		var brandThreeLevelLinkage = new mui.PopPicker({layer: 3});
		brandThreeLevelLinkage.setData(cityData3);
		fun.bindOnce('#positionReset','tap', function(event) {
			brandThreeLevelLinkage.show(function(items) {
				$("#currentPosition").html ( '选择位置：' + (items[2] || {}).text);
				BrandPosition = (items[2] || {}).text;
				var type = $(".S_M_M_header.YuYue_uptab.clearfix .border-btm").attr("search_criteria");
				var Key = $("#brandSearch input").val();
				pageFun.Get_Chessandcardroom(type,Key,BrandPosition);
				fun.setCache('ace',BrandPosition);
				fun.setCache('city',(items[0] || {}).text);
				//返回 false 可以阻止选择框的关闭
				//return false;
			});
		}, false);
		var Key = "";
		fun.bindOnce('#brandSearchBtn','tap',function(){
			var Key = $("#brandSearch input").val();
			var type = $(".S_M_M_header.YuYue_uptab.clearfix .border-btm").attr("search_criteria");
			pageFun.Get_Chessandcardroom(type,Key,BrandPosition);
		})
		
		pageFun.Get_Chessandcardroom(4,Key,BrandPosition);
		$(".S_M_M").css("background-color","#f4f4f4");
		$(".S_M_M_header li").unbind("click").click(function(){
			$(".S_M_M_header li").removeClass("border-btm");
			$(this).addClass("border-btm");
			var search_criteria = $(this).attr("search_criteria");
			var Key = $("#brandSearch input").val();
			pageFun.Get_Chessandcardroom(search_criteria,Key,BrandPosition);
		})
	},
	// Miao 2016-12-08 预约列表 待评价
	YuYue: function() {
		$("#YuYue_Ul").height($(window).height()-$(".pHead").height()-5);
		$("#YuYue_Ul").css({"overflow-y":"scroll",'-webkit-overflow-scrolling':'touch'});
		pageFun.Status_lxr(3);
		Api.post(Api.order_type,{type:3},function(obj){
			if(obj.s){
				if(obj.d == ''){
					$("#YuYue_Ul").empty();
					$("#YuYue_Ul").parent().append('<div id="evaluateNoData" style="position:absolute;color:#ff5000;font-size:0.24rem;width:100%;height:0.5rem;line-height:0.5rem;top:50%;text-align:center;">还没有待评价订单！</div>')
				}else{
					$("#evaluateNoData").remove();
					var data = obj.d;
					var html = "";
					$("#YuYue_Ul").empty();
					$.each(data,function(i,d){
						html += '<li class="content clearfix M_li"><p class="O_D_H"><span>订单号：</span><span>'+d.code+'</span><span class="fl-right">待评价</span></p>';
						$.each(d.data,function(ii,dd){
							html += '<div class="lxr_ec M_div" shop_id="'+dd.id+'" style="overflow: hidden"><img src="'+dd.listimg+'" class="tu"><p class="name">'+dd.title+'</p><p class="class">选择分类：'+dd.attr+'</p><p><span class="Price">￥'+dd.pirc+'</span><span class="fl-right number">X'+dd.num+'</span></p></div>';
						});
						html += '<p class="Price1 clearfix"><b>合计：￥'+d.cprice+'</b><a href="#/tpl_Comment2/"><span>马上评价</span></a></p></li>';
					});
					//<a href="#/Comment2/'+dd.id+'"></a> <a href="#/tpl_Comment2/"></a>
					$("#YuYue_Ul").append(html);
					var p = "";
					$("#YuYue_Ul a").unbind('tap').on('tap',function(){
						var p = "";
						$.each($(this).parents("li").find(".M_div"),function(i,d){
							p +=  '_'+$(this).attr("shop_id"); 
						})
						var l = $(this).parents("li").find(".O_D_H span:nth-child(2)").text();
						var k = l + p;
						$(this).parents("li").find("a").attr("href","#/tpl_Comment2/"+k);
					})	
				}
			}
		});
	},
	// 预约
	Order2:function(){
		Api.post(Api.shop_history, {}, function(obj) {
			if(obj.s){
				if(obj.d == ''){
					$('#Order2_content').empty();
					$("#Order2_content").parent().append('<div id="YuYueOrder" style="position:absolute;color:#ff5000;font-size:0.24rem;width:100%;height:0.5rem;line-height:0.5rem;top:50%;text-align:center;">还没有预约订单！</div>')
				}else{
					$("#YuYueOrder").remove();
					$(".score span").slice(0,5).css("color","#ff9d09");
					var u = obj.d;
					if(u && u != null && u != undefined && u != ""){
						$(".unllshow").hide();
						var y = "";
						$('#Order2_content').empty();
						$.each(u, function(i,d) {
							y += '<a href="#/tpl_Comment/' + d.shopid + '"><li class="title" num="'+d.xing+'"><span class="iconfont icon-dianpu"></span><span>'+d.shopname+'</span>';
							if(d.status > 0){
								y += '<span class="evaluate">已评价</span>';
							}else{
								y += '<span class="evaluate2">待评价</span>';
							}
							y += '</li><li class="content"><span class="C_span">下单时间：'+d.ctime+'</span><p class="one"><span>昵称：'+d.nikcname+'</span><span class="fl-right">预约人数：'+d.num+'</span></p><p>手机号：'+d.phone+'</p><p>预约时间：'+d.order_time+'</p></li></a>';
						});
						$("#Order2_content").html(y);
						$(".home-list li").each(function(i,d){
							var xing = $(this).attr("num");
	    					$(this).find(".score span").slice(0,xing).css("color","#ff9d09");						
						})
					}
				}
			}else{
				fun.tan("获取失败");
			}
		});
	},
	sjld:function(dom,fn){
		var cityPicker3 = new mui.PopPicker({layer: 3});
		cityPicker3.setData(cityData3);
		$(dom).unbind('tap').on('tap',function(){
			cityPicker3.show(function(items) {
				$(dom).parents('.BrandPosition').find('span').eq(0).text('当前位置: '+items[0].text + " " + items[1].text + " " + items[2].text);
				$(dom).attr('info',items[2].text);
				fn();
			});
		});
	},
	
	// 维修 列表
	Repair: function() {
		var lng = fun.getCache("lng");
		var lat = fun.getCache("lat");
		var ace = fun.getCache('ace');
		$(function(){
			var ace2 = ace?ace:'暂无定位 ';
			$('.MainHeadBox span').text(ace2);
			var hh = $(window).height() - $('.MainHeadBox').height() - $('.pHead.header_1').height();
			$('.RepairListBox').css({'height':hh,'padding-bottom':'0.4rem'});
		});
//		
		var cityPicker3 = new mui.PopPicker({layer: 3});
		cityPicker3.setData(cityData3);
		$('#RepairQHBtn').unbind('tap').on('tap',function(){
			cityPicker3.show(function(items) {
				$('#RepairQHBtn').parents('.MainHeadBox').find('span').eq(0).text(items[2].text);
				$('#RepairQHBtn').attr('info',items[2].text);
				var ace = $('#RepairQHBtn').attr('info');
				pageFun.RepairGetListData(lat,lng,ace);
			});
		});
		pageFun.RepairGetListData(lat,lng,ace);
	},
	RepairGetListData:function(lat,lng,ace){
		Api.post(Api.maintainer_list,{district:ace,lng:lng,lat:lat},function(obj){
			if(obj.s){
				var html = '';
				$.each(obj.d,function(i,d){
					html += '<li><a href="#/tpl_RepairListInfo/'+d.id+'"><i style="background-image:url('+d.img+');"></i><p>'+d.name+'</p>';
					html += '<p class="score" info='+d.score+' style="color:#eee;"><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span></p>';
					html += '</a></li>';
				});
				$('#RepairListBox').html(html);
				$.each($('.RepairListBox .score'),function(i,d){
					var info = $(d).attr('info');
					$(d).find("span").slice(0,info).css("color","#ff9d09");
				});
			}else{
				mui.toast(obj.m)
			}
		});
	},
	//订单详情 
	OrderDetails: function() {
		$(".btn").unbind('tap').on('tap',function() {
			$(".rgba").show();
			$(".Eject").show();
		});
		var parm = viewApi.parms;
		var code = parm[0];
		Api.post(Api.one_order,{code:code},function(obj) {
			if(obj.s){
				var d=obj.d;
				$(".order_lxr_code").text("订单编号："+d.code);
				var ostatus=null;
				switch(d.status) {
					case '0':
						ostatus = "待付款";
						break;
					case '1':
						ostatus = "待发货";
						break;
					case '2':
						ostatus = "待收货";
						break;
					case '3':
						ostatus = "待评价";
						break;
					case '4':
						ostatus = "交易完成";
						break;
					case '5':
						ostatus = "交易已关闭";
						break;
				}
				$(".order_status").text(ostatus);
				$(".order_show_ecte").empty();
				var html = "";
				$.each(d.data, function(i, dd) {
					html += '<div class="product" style="overflow: hidden;"><img src="' + dd.listimg + '" class="tu"/><p class="name">' + dd.title + dd.ds + '</p><p class="class">选择分类：' + dd.attr + '</p><p><span class="Price">￥' + dd.pirc + '</span><span class="fl-right number">X' + dd.num + '</span></p></div>';
				});
				$(".order_show_ecte").append(html);
				$('.lxr_pick_or').text("合计：￥" + d.cprice);
				$('.lxr_or_cname').text("收货人:" + d.c_name);
				$('.lxr_or_cphone').text(d.c_phone);
				$('.lxr_addr_or').text(d.c_addr);
				$('.lxr_cocoder').text(d.code);
				$('.lxr_pric_c').text("合计：￥" + d.cprice);
				paycode = d.code;
				pageFun.Pay();
			}
		});
		$(".footer0").hide();
	},
	//订单地址选择
	orderAddrlist: function() {
		$("#lxr_addrlist-btn").unbind('tap').on('tap',function() {
			$("#tpl_orderAddrlist").removeClass('popPageShow');
			viewApi.go("#tpl_addressadd");
		});
		$(".lxr_order_addrlist").unbind('click').click(function() {
			$("#tpl_orderAddrlist").hide();
			$(".Confirm_Order").show();
		});
		Api.post(Api.addr, {}, function(obj) {
			if(obj.s) {
				var o = obj.d;
				$("#lxr_address_j").empty();
				$.each(o, function(i, d) {
					if(o[i].status == 1) {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address3"><span>[默认地址]</span>' + o[i].city + o[i].pro + o[i].area + o[i].add + '</p></li>';
					} else {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address3">' + o[i].city + o[i].pro + o[i].area + o[i].add + '</p></li>';
					}
					$("#lxr_address_j").append(k);
				});
				$("#lxr_address_j li").unbind('tap').on('tap',function() {
					addressid = $(this).attr("class");
					Api.post(Api.addrone,{id:addressid},function(obj){
						if(obj.s){
							$('.lxr_c_name').text("收货人：" + obj.d.c_name);
							$('.lxr_c_phone').text(obj.d.c_phome);
							$('.lxr_paddr').text(obj.d.city + obj.d.pro + obj.d.area + obj.d.add);
							$("#tpl_orderAddrlist").hide();
							$(".Confirm_Order").show();
						} else {
							fun.tan("添加失败")
						}
					});
				});
				$("#lxr_addrlist-btn").unbind('tap').on('tap',function() {
					$("#tpl_orderAddrlist").hide();
					$(".Confirm_Order").hide();
				});
			}
		});
	},
	//确认订单
	Confirm_Order: function() {
		$(".footer0").hide();
		var parm = viewApi.parms;
		var cid = parm[0];
		var num = parm[1];
		getaddr();
		function getaddr() {
			Api.post(Api.getmaddr,{},function(obj) {
				var data = obj.d;
				if(obj.s) {
					$('.lxr_c_name').text("收货人：" + data.c_name);
					$('.lxr_c_phone').text(data.c_phome);
					$('.lxr_paddr').text(data.city + data.pro + data.area + data.add);
					$(".lxr_submit_orders").attr('aid', data.id);
					getordre();
				}else{
//					fun.setCache("cs1",1);
					viewApi.go('#tpl_addressadd');
//					location.href = "#/addressadd";
//					return false;
				}
			})
		}
		function getordre(){
			Api.post(Api.car_info,{id:cid},function(obj){
			  if(obj.s){
			  		var data=obj.d;
			  		$(".lxr_order_ok").empty();
			  		var html="";
			  		var cpric=0;
			  		$.each(data, function(i,d) {
			  			html+='<li class="content clearfix M_li2"><img src="'+d.listimg+'" class="tu"/><p class="name">'+d.ds+'</p><p class="class">选择分类：'+d.arrt+'</p><p class="M_d"><span class="Price">￥'+d.pric+'</span>';
			  			if(num){
			  				html+='<span class="fl-right number">X'+num+'</span></p></li>';
			  				cpric+=d.pric*num;
			  			}else{
				  			html+='<span class="fl-right number">X'+d.num+'</span></p></li>';			  			
				  			cpric+=d.pric*d.num;
			  			}
			  		});
			  		$('.Price1').text("合计：￥"+cpric.toFixed(2));
			  		$('.lxr_pric_c').text("￥"+cpric.toFixed(2));
			  		$(".lxr_order_ok").append(html);
			  		submit_orders(cpric);
			  	}
		  	});
		}
		$(".Consignee").unbind('tap').on('tap',function() {
			$("#tpl_orderAddrlist").show();
			$(".Confirm_Order").hide();
			
			pageFun.orderAddrlist();
		});
		function submit_orders(cpric){
			var status=false;
			$(".lxr_submit_orders").unbind('click').click(function(){
				var addid=$(".lxr_submit_orders").attr('aid');
				Api.post(Api.add_order,{cid:cid,addid:addid,cpric:cpric},function(obj){
					if(obj.s){
						$(".Eject").show();
						paycode = obj.d;
						pageFun.Pay();
					}
				})
			})
		};
	},
	//支付
	Pay: function() {
		var wxpay = false;
		var alipay = false;
		mui.plusReady(function() {
			plus.payment.getChannels(function(s) {
				payChanel = {};
				for(var i = 0; i < s.length; i++) {
					switch(s[i].id) {
						case 'wxpay':
							if(s[i].serviceReady) {
								wxpay = true;
								payChanel.wxpay = s[i];
							}
							break;
						case 'alipay':
							if(s[i].serviceReady) {
								alipay = true;
								payChanel.alipay = s[i];
							}
							break;
					}
				}
				channels = s;
			}, function(e) {
			});
		});
		$(".payment1").unbind('tap').on('tap',function() {
			$(".payment1").find(".iconfont").removeClass("icon-xuanze");
			$(this).find(".iconfont").addClass("icon-xuanze");
		});
		$(".lxr_order_pay").unbind('tap').on('tap',function() {
			var payid = $(".icon-xuanze").parent().attr('payid');
			switch(payid) {
				case 'wxpay':
					if(wxpay == false) {
						fun.tan("未安装微信");
					} else {
						pageFun.Wxpay();
					}
					break;
				case 'alipay':
					if(alipay == false) {
						fun.tan("未安装支付宝");
					} else {
						pageFun.Alipay();
					}
					break;
				default:
					fun.tan("请选择支付方式");
					break;
			}
		})
	},
	//阿里支付
	Alipay: function() {
		mui.plusReady(function() {
			Api.post(Api.getParm,{ordercode:paycode},function(obj){
				if(obj.s){
					var	statement=obj.d; 
					plus.payment.request(payChanel.alipay,statement, function(){
						fun.tan( "支付操作成功！" );
						Api.post(Api.up_order_status,{code:paycode},function(obj){
							if(obj.s){
//								location.href="#/My";
								viewApi.go('#tpl_My');
							}
						});
					}, function(e){
						fun.tan( "支付失败");
						viewApi.go('#tpl_FuKuan');
//						location.href="#/FuKuan";
					} );
				}
			});
		});
	},
	//微信支付
	Wxpay: function() {
		mui.plusReady(function() {
			Api.post(Api.getWechatParm,{ordercode:paycode},function(obj){
				if(obj.s){
					var	statement=obj.d; 
					plus.payment.request(payChanel.wxpay, statement, function(){
						fun.tan("支付操作成功！");
						Api.post(Api.up_order_status,{code:paycode},function(obj){
							if(obj.s){
								viewApi.go('#tpl_My');
							}
						});
					},function(e){
						fun.tan("支付失败");
	//					location.href="#/FuKuan";
						viewApi.go('#tpl_FuKuan');
						
					});
				}else{
					fun.tan('请求失败');
				}
			});
		});
	},
	//发起群聊
	GroupChat: function() {
		var parm = viewApi.parms;
		plp = parm[0];
		var hxuser = fun.getCache("hxUser");
//		$(".Side").css("top", "1.7rem");
		var nameid = [];
		hx.post(hx.around,{id:22},function(obj){
			if(obj.s){
				var L = obj.d;
				var k = "";
				$("#A").empty();
				$.each(L, function(o,p) {
					if(p && p.phone){
						var nameStr = p.nickname ? p.nickname : (p.phone?p.phone:'xxxx');
						k += '<li nameid="' + p.phone + '"><span class="iconfont Choice"></span><span class="portrait" style="background-image:url(' + p.img + ');"></span><span class="name">' + nameStr + '</span></li>';
					}
					$("#A").html(k);
				});
				$(".Side-main li").unbind("click").click(function() {
					if($(this).find(".Choice").is(".icon-duigou")) {
						$(this).find(".Choice").removeClass("icon-duigou");
					} else {
						$(this).find(".Choice").addClass("icon-duigou");
						var l = $(this).attr("nameid");
						nameid.push(l);
					}
				});
			}
		});
		$("#group_add_btn").unbind('tap').on('tap',function() {
			hx.post(hx.around,{id:49,group_id:plp,username:nameid},function(obj){
				if(obj.s){
					fun.tan("邀请成功");
					viewApi.back();
				}
			});
		});
		$('.Side li').unbind('tap').on('tap',function() {
			var top = $($(this).attr('t_id')).offset().top - 98;
			$('body').scrollTop(top);
		});
	},
	//联系人
	Contacts: function() {
		$(".footer9").show();
		$(".footer9 li:nth-child(2) a p").css("color", "#ff5000");
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			viewApi.go("#tpl_My");
		});
		
		$('.Side li').unbind('tap').on('tap',function() {
			var top = $($(this).attr('t_id')).offset().top - 50;
			$('body').scrollTop(top);
		});
		$("#Add_Btn").unbind('click').click(function() {
			$("#Add_list").toggleClass("list");
			if($("#Add_list").hasClass("list")) {
				$("#Add_list").fadeIn();
			} else {
				$("#Add_list").fadeOut();
			}
		});
		
		var timeout = undefined;
		pageFun.showLoading();
		
		var timeloading = setTimeout(function(){
			pageFun.closeLoading(); 
			fun.tan("请求超时");
		},20000);
		hx.post(hx.around,{id:22},function(obj){
			pageFun.closeLoading();
			clearTimeout(timeloading);
			if(obj.s){
				var L = obj.d;
				$("#A").empty();
				$.each(L,function(o,p) {
					if(p && p.phone){
						var nameStr = p.nickname ? p.nickname : (p.phone?p.phone:'xxxx');
				   		var k = '<a href="#/tpl_FS_XX/'+p.phone+'"><li nameid="'+p.phone+'"><span class="portrait" style="background:url('+p.img+');background-size:100% 100%;"></span><span class="name">'+nameStr+'</span></li></a>';
					}
//					else{
//				   		var k = '<a href="#/tpl_FS_XX/'+p.phone+'"><li nameid="'+p.phone+'"><span class="portrait" style="background:url('+p.img+');background-size:100% 100%;"></span><span class="name">'+p.phone+'</span></li></a>';
//					}
			   		$("#A").append(k);
			   		$("#A li").unbind("mousedown").bind("mousedown", function(){
			    		var nameid2 = $(this).attr("nameid");
					    timeout = setTimeout(function(){
					    	$("#XX_QD").attr("nameid",nameid2);
					    	$("#XX_Btn,.rgba").show();
					    },1500);
					});
					$("#A li").bind("mouseup", function() {
						clearTimeout(timeout);
					});
				});
			}
		});
		$("#XX_QX").unbind('tap').on('tap',function(){
			$("#XX_Btn,.rgba").hide();
		});
		$("#XX_QD").unbind('tap').on('tap',function(){
			var nameid = $(this).attr("nameid");
			var user = fun.getCache('hxUser');
			WebIMFun.removeFriends(nameid);
			hx.post(hx.delFriend,{name:user,toname:nameid},function(obj){});
			$.each($("#A li"),function(i){
				var nameid2 = $("#A").find("li").eq(i).attr("nameid");
				var nameid3 = $("#A").find("li").eq(i);
				if(nameid2 == nameid) {
					nameid3.remove();
					$("#XX_Btn,.rgba").hide();
				}
			});
		});
	},
	//
	pre_focus:function(){
		//pre 能够获取焦点
	 	var editor = document.getElementById('text_content');
	 	$("#text_content").unbind('tap').on('tap',function(){
			editor.focus();
			$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop()); 
	 	})
		editor.onfocus = function () {
			window.setTimeout(function () {
				var sel,range;
				if (window.getSelection && document.createRange) {
					range = document.createRange();
					range.selectNodeContents(editor);
					range.collapse(true);
					range.setEnd(editor, editor.childNodes.length);
					range.setStart(editor, editor.childNodes.length);
					sel = window.getSelection();
					sel.removeAllRanges();
					sel.addRange(range);
				} else if (document.body.createTextRange) {
					range = document.body.createTextRange();
					range.moveToElementText(editor);
					range.collapse(true);
					range.select();
				}
			}, 1);
		};
	},
	//发送消息 Miao 2016-12-09
	FS_XX: function() {
		var parm = viewApi.parms;
		plp = parm[0];
		var hxuser = fun.getCache("hxUser");
		var mesList = fun.getCache('mesList');
		var asd = $(window).height();
		$(".page").css({"overflow":"hidden","height":asd});
//		$(".input-text").css("height","200px")
		$(".icon-yuyin").css("margin-right","0.35rem");
		//监测输入框是否输入
		var input_Group = document.getElementById("text_content");
		var Btn_Group = document.getElementById("text_btn");
		input_Group.onkeyup = function(){
			Btn_Group.style.display = "block";
			if($("#text_content").html() == ""){
				Btn_Group.style.display = "none";
				$("#Group_icon").show();
			}
		}
		
		$("#main").css("height",$(window).innerHeight()-$('.header_1').height()-$(".input-text").height());
		pageFun.pre_focus();
		//表情
		var bq = new BQ();
	 	$('.icon-biaoqing').unbind('click').click(function(){
	 		$(this).toggleClass("BQ_KG");
	 		var _this = this;
	 		if($(this).hasClass("BQ_KG")){
			 	bq.showBQ();
				bq.onSelect(function(obj){
					$('#text_content').append('<img src="'+obj.img+'" />');
				});
				$("#bq dl dd").unbind('tap').on('tap',function(){
					Btn_Group.style.display = "block";
//					$("#Group_icon").css("display","none");
					$(_this).toggleClass("BQ_KG");
					var editor = document.getElementById('text_content');
					editor.focus();
					$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
				});
	 		}else{
	 			bq.hideBQ();
	 		}
	 	});
		$("#Group_content").focus(function(){
	 		setTimeout(function(){
	 			$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
	 		},1000)
	 	});
		pageFun.post_yuyin();
		
		pageFun.Get_history_information();
		hx.post(hx.head_img,{fname:plp},function(obj){
			if(obj.s){
				myimg = obj.d.my;
				other = obj.d.other;
				if(obj.d.nickname) {
					$("#Friendname").text(obj.d.nickname);
				} else {
					$("#Friendname").text(plp);
				}
			}
		});
//		单聊发送消息
		$("#text_btn").unbind('tap').on('tap',function() {
			var content = $("#text_content").html();
			var max_height = $(window).innerHeight() + 'px';
			if(content != null && content != undefined && content != "") {
				$("#text_content").html("");
				pageFun.gt(1,plp,1,hxuser);//ok
				WebIMFun.doSendMesTo(plp, content, function(id, serverMsgId) {});
				hx.post(hx.around,{id:71,from:hxuser,to:plp,chat_type:'chat',msg:content},function(obj){
					if(obj.s){
						fun.tan('发送成功');
					}
				});
				var p = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + myimg + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + content + '</pre></div></div>';
				$("#main").append(p);
				pageFun.ScrollBottom('#main');
				var editor = document.getElementById('text_content');
				editor.focus();
				$("#text_btn").hide();
				$("#Group_icon").show();
			} else {
				fun.tan("消息不能为空");
			}
		});
		
		asd_from = fun.getCache("hxUser");
		pageFun.asd("#FS_XX_icon");
		$('#main').height($(window).height()-$('.header_1').height()-$(".input-text").height());
	},
	ScrollBottom:function (DomId){
		var DomLength =  $(DomId).children().length;
		if(DomLength > 0){
			$("#ScrollTopTop").attr('id','');
			$(DomId).children().last().attr('id','ScrollTopTop');
			document.getElementById('ScrollTopTop').scrollIntoView(0);
		}else{
			
		}
	},
//	聊天上传图片
	asd:function(icon_id){
		$(icon_id).unbind('tap').on('tap',function(){
			var btnArray = ['否', '是'];
			mui.confirm('是否选择照相机', '您好', btnArray, function(e) {
				if(e.index == 1){
					//摄像头
					fun.photo();
				}else{
					mui.plusReady(function() {
						plus.gallery.pick(function(img){
							onchenage(img);
						},function(error){
						},{filter:"image"});
					});
				}
			});
		});
		function dataURLtoBlob(dataurl) {
		    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
		    while(n--){
		        u8arr[n] = bstr.charCodeAt(n);
		    }
		    return new Blob([u8arr], {type:mime});
		}
		function onchenage(img){
			var imgDOM = new Image();
			imgDOM.onload = function(){
				var _this = this;
				var dat = appendFile(img,function(dat){
					EXIF.getData(_this,function(){
		                EXIF.getAllTags(this);
		                Orientation = EXIF.getTag(this,'Orientation');
						compareImage(dat,function(data){
							isOK = true ;
							var k = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + myimg + ');"></i><div class="content content2"><i class="icon-bgd"></i><img src="'+data+'" /></div></div>';
		                	$("#main").append(k);
							$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
							var from = fun.getCache("hxUser");
							if(plp.length > 11){
								var type = "chatgroups";
								var type2 = 'groupchat';
							}else{
								var type = 'users';
								var type2 = 'chat';
							}
			                hx.post(hx.sendImage,{data:data,from:from,people:plp,to:plp,target_type:type,chat_type:type2},function(obj){
					        	if(obj.s){
					        		if(plp.length > 11){
										pageFun.gt(2,plp,1,from); //ok
									}else{
										pageFun.gt(1,plp,1,from); //ok
									}
					        		fun.tan("发送成功");
									$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
									pageFun.click_img();
					        	}else{
					        		fun.tan(obj.m);
					        	}
					        })
						});
		            }); 
		        });
			}
			imgDOM.src= img;
		}
		function compareImage(imgSource,fn){
			var mW = 400, mH = 300;
			var img = new Image();
			img.onload = function(){
				var sH = img.height;
				var sW = img.width;
				var bl = 1;
				if(sH>mH || sW>mW){
					bl = (sW/mW>sH/mH) ? mW/sW : mH/sH ;
				}
				var ssW = parseInt(sW*bl);
				var ssH = parseInt(sH*bl);
				var canvas = document.createElement('canvas');
				canvas.id="myCanvas";
				canvas.width = ssW;
				canvas.height = ssH;
				var ctx=canvas.getContext('2d');
				ctx.drawImage(img,0,0,sW,sH,0,0,ssW,ssH); 
				var base64 = null;  
                //修复ios  
//              if (navigator.userAgent.match(/iphone/i)){
                    if(Orientation != "" && Orientation != 1 && Orientation){
                        //alert('旋转处理');  
                        switch(Orientation){  
                            case 6://需要顺时针（向左）90度旋转  
                                //alert('需要顺时针（向左）90度旋转');  
                                rotateImgs(this,'left',canvas);  
                                break;  
                            case 8://需要逆时针（向右）90度旋转  
                                //alert('需要顺时针（向右）90度旋转');  
                                rotateImgs(this,'right',canvas);  
                                break;  
                            case 3://需要180度旋转  
                               // alert('需要180度旋转');  
                                rotateImgs(this,'right',canvas);//转两次  
                                rotateImgs(this,'right',canvas);  
                                break;  
                        }         
                    }  
//				}
				var dat = canvas.toDataURL('image/jpeg',1);
				fn(dat);
			}
			img.src = imgSource;
		}

	//对图片旋转处理
	function rotateImgs(img, direction,canvas) {    
        //最小与最大旋转方向，图片旋转4次后回到原方向    
        var min_step = 0;    
        var max_step = 3;    
        //var img = document.getElementById(pid);    
        if (img == null)return;    
        //img的高度和宽度不能在img元素隐藏后获取，否则会出错    
        var height = img.height;    
        var width = img.width;    
        //var step = img.getAttribute('step');    
        var step = 2;    
        if (step == null) {    
            step = min_step;    
        }    
        if (direction == 'right') {    
            step++;    
            //旋转到原位置，即超过最大值    
            step > max_step && (step = min_step);    
        } else {    
            step--;    
            step < min_step && (step = max_step);    
        }    
        //旋转角度以弧度值为参数    
        var degree = step * 90 * Math.PI / 180;    
        var ctx = canvas.getContext('2d');    
        switch (step) {
            case 0:    
                canvas.width = width;    
                canvas.height = height;    
                ctx.drawImage(img, 0, 0);    
                break;    
            case 1:    
                canvas.width = height;    
                canvas.height = width;    
                ctx.rotate(degree);    
                ctx.drawImage(img, 0, -height);    
                break;    
            case 2:    
                canvas.width = width;    
                canvas.height = height;    
                ctx.rotate(degree);    
                ctx.drawImage(img, -width, -height);    
                break;    
            case 3:    
                canvas.width = height;    
                canvas.height = width;    
                ctx.rotate(degree);    
                ctx.drawImage(img, -width, 0);    
                break;
        }
    	}
		function appendFile(path,fn){
		  	var img = new Image();
	        img.src = path;        // 传过来的图片路径在这里用。
	        img.onload = function () {
	            var that = this;
	            //生成比例 
	            var w = that.width,
	                h = that.height,
	                scale = w / h; 
	                w = 480 || w;              //480  你想压缩到多大，改这里
	                h = w / scale; 
	            var canvas = document.createElement('canvas'); 
	            var ctx = canvas.getContext('2d'); 
	            $(canvas).attr({width : w, height : h}); 
	            ctx.drawImage(that, 0, 0, w, h); 
	            var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8 );  
	           	fn(base64);
		    }
		}
	},
	//点击显示大图
	click_img:function(){
		$(".content2 img").unbind('tap').on('tap',function(){
			var _src = $(this).attr("src");
			var k = '<div style="position:relative;position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.8);z-index:9999;" id="click_rgba"><img src="'+_src+'" style="width:100%;z-index:9999;position:absolute;top:50%;left:50%;transform: translate(-50%,-50%);" /></div>';
			$("#main").parent().append(k);
			$("#click_rgba , #click_rgba img").unbind("tap").on('tap',function(){
				$(this).remove();
				$(this).find("img").remove();
			})
		})
	},
	//发送语音
	post_yuyin:function(){
		//语音消息
		var r=null,t=0,ri=null,rt=null , tmer; 
		var tmer = null;
		var savePath = '';
		$(".icon-yuyin").unbind('tap').on('tap',function(){
			$('#startRecordBtn , #recordBox').fadeIn(function(){
				$('#startRecordBtn').unbind('tap').on('tap',function(){
//					$('#startRecordBtn').hide();
//					$('#endRecordBtn').show();
					$("#recordBox .Dot").addClass("smile");
					$(".Dot_text").text("点击停止");
					$('#startRecordBtn').unbind('tap').on('tap',function(){
						clearInterval( ri );
						ri = null;
						r.stop();
						t = 0;
						$("#recordBox .Dot").removeClass("smile");
						$(".Dot_text").text("");
//						$('#startRecordBtn,.circular').hide();
						$('.recordEnd').show();
						$(".off_yuyin").hide();
						//试听按钮
						$('#viewRecordBtn').unbind('tap').on('tap',function(){
							var plar = plus.audio.createPlayer( savePath );
							var tmer = null;
							plar.play( function () {
								// 播放完成 off_yuyin 
								clearInterval(tmer); 
							}, function ( e ) {
							} ); 
							tmer = setInterval(function(){},100);
						});
						$('#sendRecordBtn').unbind('tap').on('tap',function(){
							$('.recordEnd , #recordBox').hide();
							plus.io.resolveLocalFileSystemURL(savePath, function(entry){ 
						        entry.file(function(file){
						            var reader = new plus.io.FileReader();
						            reader.onloadend = function (e) {
						            	var fromphone = fun.getCache("hxUser");
						            	var tophone = plp;
						            	if(plp.length > 11){
						            		var type_content = "chatgroups";
						            		var type2 = 'groupchat';
						            	}else{	
						            		var type_content = "users";
											var type2 = 'chat';
						            	}
						                hx.post(hx.sendAudio,{data:e.target.result,from:fromphone,to:tophone,target_type:type_content,chat_type:type2},function(obj){
						                	if(obj.s){
												pageFun.addAudioMesToList(savePath,obj.d);
						                		if(plp.length > 11){
						            				pageFun.gt(2,plp,1,fromphone); //ok
						            			}else{	
						            				pageFun.gt(1,plp,1,fromphone);
						            			}
						                	} 
						                });
						            };
						            reader.readAsDataURL(file.fullPath);
						        },function(e){
						        })
						    });
						}); 
					});
					r = plus.audio.getRecorder();
					if ( r == null ) {
						return;
					} 
					r.record( {filename:"_doc/audio/"}, function ( p ) { 
						savePath = p;
						return false; 
					}, function ( e ) {
					} );
				});
			});
			$(".off_yuyin,#sendRecordBtn2 .icon-cha").unbind('tap').on('tap',function(){
				$('#startRecordBtn , #recordBox , .recordEnd').fadeOut();
				$(".Dot").removeClass("smile");
			});
		});
	},
	//下载语音
	download:function(message,fn){
		var options = {
			url: message,
			onFileDownloadComplete:function( response ){
		      	var res = URL.createObjectURL(response);
		      	var tmpmessage = {
//		      		id:message.id,
//		      		type:message.type,
		      		src:res,
//		      		from:message.from,
//		      		to:message.to,
//		      		time:message.time,
		      		newsType:"audio"
		      	}
		      	fn(tmpmessage);  
		    },
		    onFileDownloadError:function(){},
		    headers:{'Accept':'audio/mp3'}
		};
	    WebIM.utils.download.call(IMconn, options);
	},
	//发送语音
	addAudioMesToList:function(path,url){
		var p = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + myimg + ');"></i><div class="content audioMes postmsg" d_path="'+url+'"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+url+'"></audio></i></div></div>';
		$("#main").append(p);
		$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
		$(".postmsg").unbind('tap').on('tap',function(){
//			$(".content").find(".audio_news").trigger("stop");
//			$(this).find(".audio_news").trigger("play");
			var Audiourl = $(this).find(".audio_news").attr('src');
			pageFun.playAudio(Audiourl);
		});
	},
	//收到语音消息
	Voice:function(obj,VoiceHeadImg){
//		pageFun.My_news();
		$(".footer9").hide();
		var hxuser = fun.getCache("hxUser");
		if(obj.type == "groupchat"){
//			var img = 'http://yzl.lxrbk.com/Public/upload/userimg/t.jpg'; //pageFun.getMemberImg(obj.from);
			var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + VoiceHeadImg + ');"></i><div class="content Voicemsg"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+obj.src+'"></audio></i></div></div>';
			$("#main").append(p);
			$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
			$(".Voicemsg").unbind('tap').on('tap',function(){
				$(".content").find(".audio_news").trigger("stop");
				$(this).find(".audio_news").trigger("play");
//				var Audiourl = $(this).find(".audio_news").attr('src');
//				pageFun.playAudio(Audiourl);
			});
		} else if(obj.type == "chat") {
			if(obj.from == plp) {
				var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + other + ');"></i><div class="content Voicemsg"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+obj.src+'"></audio></i></div></div>';
				$("#main").append(p);
				$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
				$(".Voicemsg").unbind('tap').on('tap',function(){
					$(".content").find(".audio_news").trigger("stop");
					$(this).find(".audio_news").trigger("play");
				});
			}
		}
	},
	//图片
	img_news:function(obj,fnameImg){
		$(".footer9").hide();
		var hxuser = fun.getCache("hxUser");
		if(obj.type == "groupchat"){
//			var img = 'http://yzl.lxrbk.com/Public/upload/userimg/t.jpg'; //pageFun.getMemberImg(obj.from);
			var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + fnameImg + ');"></i><div class="content content2" style="background-color:transparent;"><i class="icon-bgd"></i><img src="'+obj.src+'" /></div></div>';
			$("#main").append(p);
			$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
		} else if(obj.type == "chat") {
			if(obj.from == plp) {
				var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + other + ');"></i><div class="content content2"><i class="icon-bgd"></i><img src="'+obj.src+'" /></div></div>';
				$("#main").append(p);
				$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
//				$(".content").unbind('tap').on('tap',function(){
//					$(this).find(".audio_news").trigger("play");
//				});
			}
		}
	},
	//群聊天  qunliaotian
	Group_text: function() {
		if(viewApi.parms.length<2) return false;
		var parm = viewApi.parms;
		plp = parm[0];
		
		var hxuser = fun.getCache("hxUser");
		//pre 能够获取焦点
	 	var editor = document.getElementById('Group_content');
	 	$("#Group_content").unbind('tap').on('tap',function(){
			editor.focus();
	 	});
		$("#main").height($(window).innerHeight()-$(".pHead").height()-$(".input-text").height()-3);
	 	
		editor.onfocus = function () {
			window.setTimeout(function () {
				var sel,range;
				if (window.getSelection && document.createRange) {
					range = document.createRange();
					range.selectNodeContents(editor);
					range.collapse(true);
					range.setEnd(editor, editor.childNodes.length);
					range.setStart(editor, editor.childNodes.length);
					sel = window.getSelection();
					sel.removeAllRanges();
					sel.addRange(range);
				} else if (document.body.createTextRange) {
					range = document.body.createTextRange();
					range.moveToElementText(editor);
					range.collapse(true);
					range.select();
				}
			}, 1);
		};
		pageFun.post_yuyin();
		
		pageFun.Get_history_information2();
		
		//表情
		var input_Group = document.getElementById("Group_content");
		var Btn_Group = document.getElementById("Group_btn");
		input_Group.onkeyup = function(){
			Btn_Group.style.display = "block";
			if($("#Group_content").html() == ""){
				Btn_Group.style.display = "none";
				$("#Group_icon").show();
			}
		}
		$("#bq dd").unbind('tap').on('tap',function(){
			Btn_Group.style.display = "block";
		});
		var bq = new BQ();
	 	$("#Group_content").focus(function(){
	 		setTimeout(function(){
	 			$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
	 		},1000);
	 	})
	 	
	 	$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
	 	
	 	$('.icon-biaoqing').unbind('click').click(function(){
	 		$(this).toggleClass("BQ_KG");
	 		var _this = this;
	 		if($(this).hasClass("BQ_KG")){
			 	bq.showBQ();
				bq.onSelect(function(obj){
					$('#Group_content').append('<img src="'+obj.img+'" />');
				});
				$("#bq dl dd").unbind('tap').on('tap',function(){
					Btn_Group.style.display = "block";
					$(_this).toggleClass("BQ_KG");
					var editor = document.getElementById('Group_content');
					editor.focus();
				});
	 		}else{
	 			bq.hideBQ();
	 		}
	 	});
		hx.post(hx.head_img,{fname:plp},function(obj){
			if(obj.s){
				myimg = obj.d.my;
				other = obj.d.other;
				if(obj.d.nickname){
					$("#Friendname").text(obj.d.nickname);
				}else{
					$("#Friendname").text(plp);
				}
			}
		});
		$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
		$("#Ground_Set_up").unbind('tap').on('tap',function() {
			viewApi.go('#tpl_Chat',[plp]);
		});
		//发送消息
		$("#Group_btn").unbind('tap').on('tap',function() {
			var content = $("#Group_content").html();
			if(content != null && content != undefined && content != "") {
				//				var p = '<div class="clearfix ctt2"><i class="header-img" style="background:url();">头像</i><div class="content"><i class="icon-bgd"></i><p>'+content+'</p></div></div>';
				//				$("#main").append(p);
				$("#Group_content").html("");
				pageFun.gt(2,plp,1,hxuser); //ok
				WebIMFun.sendGroupText(plp,content,function(id,serverMsgId){});
				hx.post(hx.around,{id:71,from:hxuser,to:plp,chat_type:'groupchat',msg:content},function(obj){
					if(obj.s){
						fun.tan('发送成功');
					}
				});
				var p = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + myimg + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + content + '</pre></div></div>';
				$("#main").append(p);
				var editor = document.getElementById('Group_content');
					editor.focus();
				$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
				if($("#Group_content").html() == ""){
					Btn_Group.style.display = "none";
					$("#Group_icon").show();
				}
			} else {
				fun.tan("消息不能为空");
			}
		});
		asd_from = fun.getCache("hxUser");
		pageFun.asd("#Group_icon");
		$('#main').height($(window).height()-$('.header_1').height()-$(".input-text").height());
	},
	//获取群历史消息
	Get_history_information2: function() {
		var hxuser = fun.getCache("hxUser");
		var parm = viewApi.parms;
		var plp = parm[0]; //群id
		var plp2 = decodeURI(parm[1]); // 群名称
		$("#Groundname").text(plp2);
		if(!plp2){
			$("#Groundname").text(plp);
		}
		var bq = new BQ();
		hx.post(hx.history_msg,{type:2,name:hxuser,fname:plp},function(obj){
			if(obj.s){
				var u = obj.d;
				$("#main").empty();
				$.each(u,function(i,d){
					if(d.from == hxuser){
						if(d.type == "audio"){
							var p = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+d.url+'"></audio></i></div></div>';
						}else if(d.type == "img"){
							var p = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content content2"><i class="icon-bgd"></i><img src="'+d.url+'" /></div></div>';
						}else if(d.type == "txt"){
							var p = '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + d.content + '</pre></div></div>';
						}
						$("#main").append(p);
					}else{
						if(d.type == "audio"){
							var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+d.url+'"></audio></i></div></div>';
						}else if(d.type == "img"){
							var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content content2"><i class="icon-bgd"></i><img src="'+d.url+'" /></div></div>';
						}else if(d.type == "txt"){
							var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + d.content + '</pre></div></div>';
						}
						$("#main").append(p);
					}
//					$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
				});
				pageFun.ScrollBottom('#main');
				pageFun.click_img();
				$(".content").unbind("click").click(function(){
//					$(".audio_news").trigger("pause");
//					$(this).find(".audio_news").trigger("play");
					var Audiourl = $(this).find(".audio_news").attr('src');
					pageFun.playAudio(Audiourl);
				});
				$.each($("#main").find(".audio_news"),function(i,d){
					src_html = $(this).attr("src");
					var _this = $(this);
//					pageFun.download(src_html,function(res){
//						_this.attr("src",res.src);
//					})
				});
			}
		});

	},
	
	playAudio:function(url){
		AudioPlayAmr = plus.audio.createPlayer(url);
		var num = AudioPlayAmr.getDuration(); //获取音频总长度number
		setTimeout(function() { //延时获取，否则可能没有返回长度
			var num = AudioPlayAmr.getDuration();
		}, 100);
		AudioPlayAmr.play(function() { //播放完成回调
//			console.log("Audio play success!");
		}, function(e) { //失败回调
			console.log("Audio play error: " + e.message);
		});
	},
	
	//获取个人历史消息
	Get_history_information: function() {
		var hxuser = fun.getCache("hxUser");
		var parm = viewApi.parms;
		plp = parm[0];
		var bq = new BQ();
		hx.post(hx.history_msg,{type:1,name:hxuser,fname:plp},function(obj){
			if(obj.s){
				var u = obj.d;
				$("#main").empty();
				var p = '';
				$.each(u, function(i,d) {
					if(d.from == hxuser) {
						if(d.type == "audio"){
							p += '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+d.url+'"></audio></i></div></div>';																																					
						}else if(d.type == "img"){
							p += '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content content2"><i class="icon-bgd"></i><img src="'+d.url+'" /></div></div>';
						}else if(d.type == "txt"){
							p += '<div class="clearfix ctt2"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + d.content + '</pre></div></div>';
						}
					} else {
						if(d.type == "audio"){
							p += '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><i class="iconfont icon-yuyin-copy"><audio class="audio_news" preload src="'+d.url+'"></audio></i></div></div>';
						}else if(d.type == "img"){
							p += '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content content2"><i class="icon-bgd"></i><img src="'+d.url+'" /></div></div>';
						}else if(d.type == "txt"){
							p += '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + d.img + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + d.content + '</pre></div></div>';
						}
					}
				});
				$("#main").html(p);
				pageFun.ScrollBottom("#main");
				pageFun.click_img();
				$(".content").unbind("tap").on('tap',function(){
					var Audiourl = $(this).find(".audio_news").attr('src');
					pageFun.playAudio(Audiourl);
				});
				$.each($("#main").find(".audio_news"),function(i,d){
					src_html = $(this).attr("src");
					var _this = $(this);
				});
				setTimeout(function(){ $('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop()); },10000);
			}
		});
	},
	//收到文本消息
	addMesLog:function(mObj){
//		pageFun.My_news();
		var bq = new BQ();
		$(".footer9").hide();
		var hxuser = fun.getCache("hxUser");
		var from = mObj.from;
		hx.post(hx.head_img,{fname:from},function(obj){
			if(obj.s){
				var u = obj.d;
				var other_img_header = u.other;
				if(mObj.type == "groupchat"){
					var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url('+ other_img_header +');"></i><div class="content"><i class="icon-bgd"></i><pre>' + mObj.data + '</pre></div></div>';
					$("#main").append(p);
					$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
				} else if(mObj.type == "chat") {
					if(mObj.from == plp) {
						var p = '<div class="clearfix ctt"><i class="header-img" style="background-image:url(' + other + ');"></i><div class="content"><i class="icon-bgd"></i><pre>' + mObj.data + '</pre></div></div>';
						$("#main").append(p);
						$('#main').scrollTop(($('#main .clearfix:last-child').length>0?$('#main .clearfix:last-child').offset().top:0)+$(window).height()+$('#main').scrollTop());
					}
				}
			}
		});
	},
	
	
	
	//我的消息
	My_news: function() {
		var bq = new BQ();
		$(".footer9").show();
		$("html,body,.mypage,.container").css("height","auto");
		$(".footer9 ul li:nth-child(1) a p").css("color","#ff5000");
		var myHx = fun.getCache('hxUser');
		var mesList = fun.getCache('mesList');
		var html = '';
		var AddFimg = [];
		pageFun.showLoading();
		$('#nmesList').height($(window).height()-$('.header_1').height()-$('.footer9').height()).addClass('scroll');
		var timeloading = setTimeout(function(){
			pageFun.closeLoading();
			fun.tan("请求超时");
		},20000);
		$.each(mesList, function(i, d) {
			if(d.type && d.type == 'subscribe') { //当信息类型是关注的时候
				html += '<li class="TZ-top clearfix AddF" from="' + d.from + '"><i><span></span></i><p><span>' + d.from + '</span><br><span class="time_font">2016-06-12 12:35</span></p><p class="add addfBtn" d_index="' + i + '" d_id="' + d.from + '" c_id="' + d.to + '">同意</p></li>';
				AddFimg.push(d.from);
			}
		});		
		//请求返回账号名下所有的聊天记录的最后一条，并插入我的消息页面中
		hx.post(hx.msg_list,{name:myHx},function(obj){
			pageFun.closeLoading();
			clearTimeout(timeloading);
			if(obj.s){
				var u = obj.d;
				var k = '';
				$.each(u, function(i,d) {
					if(d.to.length > 11 || d.from.length > 11){
						k += '<li class="TZ-top clearfix"><a href="#/tpl_Group_chat';
						k += '/'+d.to+'/'+d.to_nickname+'">';
					}else{
						k += '<li class="TZ-top clearfix"><a href="#/tpl_FS_XX';
						if(d.to == myHx){
							k += '/'+d.from+'">';
						}else{
							k += '/'+d.to+'">';
						}
					}
					if(d.to == myHx){
						k += '<i style="background-image:url('+d.from_img+')"></i><div class="div_style">';
					}else if(d.from == myHx){
						k += '<i style="background-image:url('+d.to_img+')"></i><div class="div_style">';
					}
					if(d.from == myHx){
						if(d.to_nickname){
							k += '<span>'+d.to_nickname+'</span><br>';
						}else{
							k += '<span>'+d.to+'</span><br>';
						}
					} else {
						if(d.from_nickname) {
							k += '<span>' + d.from_nickname + '</span><br>';
						} else {
							k += '<span>' + d.from + '</span><br>';
						}
					}
					if(d.type == "audio"){
						k += '<p class="Voice">[语音]</p></div><p class="news_time time_font">' + d.ctimeStr + '</p>';
					}else if(d.type == "img"){
						k += '<p class="Voice">图片</p></div><p class="news_time time_font">' + d.ctimeStr + '</p>';
					}else if(d.type == "txt"){	
						k += '<pre>' + d.msg + '</pre></div><p class="news_time time_font">' + d.ctimeStr + '</p>';
					}
					if(d.unread != 0){
						k += '<div class="news_Unread">'+d.unread+'</div></a></li>';
					}else{
						k += '</a></li>';
					}
					AddFimg.push(d.from);
				});
				$('#nmesList').append(k);
			}
		});
		hx.post(hx.head_imgs,{phone:AddFimg},function(obj){
			if(obj.s){
				var u = obj.d;
				var y = u.phone;
				$(".AddF").each(function(i) {
					$(this).find("i").attr("style", "background-image:url(" + u[i].img + ")");
				});
			}
		});
		$("#nmesList a").unbind('tap').on('tap',function() {
			$(this).find("i").find("span").remove();
		});
		$('#nmesList').html(html);
		//收到好友请求 同意按钮
		$('.addfBtn').unbind('click').click(function() {
			var you = $(this).attr('d_id');
			var idx = $(this).attr('d_index');
			var myHx = $(this).attr("c_id");
			var mesList = fun.getCache('mesList');
			hx.post(hx.around,{id:20,name:myHx,fname:you},function(obj){
				if(obj.s){
					pageFun.Array_remove();
					mesList.remove(idx);
					fun.setCache("mesList", mesList);
//					location.href="#/Contacts";
					viewApi.go("#tpl_Contacts")
				}
			});
			var mesList = fun.getCache("mesList");
			$(this).parents('li.TZ-top').remove();
		});
	},
	//数组添加remove方法 删除
	Array_remove:function(){
		Array.prototype.remove=function(dx){ 
		    if(isNaN(dx)||dx>this.length){return false;} 
		    for(var i=0,n=0;i<this.length;i++){ 
		        if(this[i]!=this[dx]){
		            this[n++]=this[i] 
		        } 
		    } 
		    this.length-=1 
		} 
	},
	//在其他页面收到文本消息
	onSubscribe: function(mes) {
		if(mes.type == 'subscribe'){
			if(mes.status == "" || mes.status == null || mes.status == undefined){
				mui.toast(mes.from + '请求加你为好友');
			}else{
				mui.toast(mes.from + mes.status);
			}
			var mesList = fun.getCache('mesList') || [];
			var string = '_';
			$.each(mesList, function(i,d) {
				string += d.from+"_";
			});
			var ifString = string.indexOf('_'+mes.from);
			if(ifString < 0){
				mesList.push(mes);
				fun.setCache('mesList', mesList);
			}
		}
	},
	//群聊信息 miao 2016-12-15
	Chat: function(){
		//if(viewApi.parms.length<1) return false;
		var parm = viewApi.parms;
		plp = parm[0];
		
		
		pageFun.ios_window('rgba(184,100,55,0.9)','UIStatusBarStyleDefault');
		var hxuser = fun.getCache("hxUser");
		$(".Chat-header").show();
		fun.bindOnce("#group_Chat_setup",'tap',function() {
			viewApi.go("#tpl_qun",plp);
//			location.href = "#/qun/" + plp + "";
		});
		$("#Chat_main").height($(window).height()-$(".Chat-header").height()-10);
		hx.post(hx.around,{id:2,group_num:plp},function(obj){
			if(obj.s){
				var u = obj.d;
				$("#group_setup_name").text(u.name);
				$("#group_id").text("ID:" + u.id);
				$("#group_introduce").text(u.description);
				$("#group_img").css("background-image", "url(" + u.group_img + ")");
				$(".number2").text(u.affiliations_count + "人");
				var member = u.affiliations;
				var k = "";
				$("#Add_this").empty();
				$.each(member, function(i, d){
					k += '<i class="t1" style="background-image:url(' + d.img + ')"></i>';
				});
				$("#Add_this").html(k);
				fun.bindOnce("#Add_group_member",'tap',function() {
//					location.href = "#/GroupChat/" + u.id + "";
					viewApi.go("#tpl_GroupChat",u.id);
				});
				hx.post(hx.del_msg,{name:hxuser,toname:plp},function(obj){
					if(obj.s){}
				})
			}
		});
		$("#Out_Group").unbind('tap').on('tap',function(){
			hx.post(hx.around,{id:4,groupid:plp,name:hxuser},function(obj){
				if(obj.s){
					hx.post(hx.delFriend,{name:hxuser,toname:plp},function(obj){
						if(obj.s){
							viewApi.go('#Group');
						}
					});
				}
			})
		});
	},
	//发帖
	Post:function(){		
		$(".Post-main .tu").remove();
		$('.upfile').unbind('change').on('change',function() {
			if($('.Post-main .tu').length<3){
				var _this = this;
				var file = document.getElementById($(this).attr('id')).files[0];
				var fr = new FileReader();
				fr.onload = function(res) {
					$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ');margin:0.2rem 0 0 0.2rem;" imgdata=' + res.target.result +'><span class="remove">删除</span></li>');
					$(".remove").unbind('tap').on('tap',function() {
						$(this).parents(".tu").remove();
					});
				}
				fr.readAsDataURL(file);
			}else{
				fun.tan('不能超过三张')
			}
		});
		$("body").removeClass("body_height");
		$("html,body,.mypage,.container,.Post").css("height","100%");
		$('.plate').unbind('tap').on("tap",function(){
			Api.post(Api.tie_model,{},function(obj){
				if(obj.s){
					var data=[];
					$.each(obj.d, function(i,d){
						data.push({ value: d.id,text: d.category});
					});
					var picker = new mui.PopPicker();
					picker.setData(data);
					picker.pickers[0].setSelectedValue('fourth', 2000);
					picker.show(function(SelectedItem) {
						$('.tie_model').html(SelectedItem[0].text + '<span class="iconfont">&#xe62b;</span>').attr('vl', SelectedItem[0].value);
					})
				}
			});
		});
		var kg = true;
		$(".btn2").unbind('tap').on('tap',function() {
			var title = $("#bbs_title").val();
			var content = $('#bbs_content').val();
			var cid = $('.tie_model').attr('vl');
			if(title == "") {
				fun.tan('标题不能为空');
				return false;
			}
			if(content == "") {
				fun.tan('内容不能为空');
				return false;
			}
			if(cid == 0) {
				fun.tan('请选择版块');
				return false;
			}
			var yyzz = '';
			$("#PostImgId").parents('ul').find(".tu").each(function(i) {
				var listimg5 = $("#PostImgId").parents('ul').find(".tu").eq(i).attr("imgdata");
				yyzz+= "@" + listimg5;
			});
			yyzz = yyzz.substr(1);
			if(kg == true){
				kg = false;
				Api.post(Api.add_tie,{title:title,content:content,cid:cid,img:yyzz},function(obj){
					if(obj.s){
	//					location.href = "#/Community";
						viewApi.go("#community");
					}else{
						kg = true;
					}
				});
			}
		});
	},
	Gpsaddr: function(){
		var cityPicker3 = new mui.PopPicker({layer: 3});
		cityPicker3.setData(cityData3);
		fun.bindOnce('.position1','tap',function(event){
			cityPicker3.show(function(items) {
				$(".position1 b:first").text(items[2].text);
				fun.setCache("ace",items[2].text);
				fun.setCache("city",items[1].text);
				pageFun.getPlace(".position1",items[0].text+items[1].text+items[2].text,items[0].text);
				pageFun.homebottomlist();
			});
		}, false);
	},
	indexshow:function(){
//		var ace=fun.getCache("ace");
//		Api.post(Api.shop_listtop,{ace:ace},function(obj){
//			if(obj.s){
//				var p = obj.d;
//				$("#HomeScrollUl").empty();
//				var k = "";
//				k += '<li style="height:0.55rem;border-bottom:1px solid #dadada;line-height:0.55rem;padding:0 0.2rem;"><span style="font-size:0.22rem;color:#f00;float:left;">热门店铺</span><span style="float:right;font-size:0.16rem;color:rgba(34,34,34,.45);" id="HomeViewMore" >查看更多>></span></li>';
//				$.each(p, function(i,d) {
//					k += '<li class="clearfix" num="'+d.xing+'"><a href="#/tpl_shop/' + p[i].id + '"><img src="'+ p[i].listimg +'" /><div><p class="shop_name">' + p[i].shopname + '</p><p class="score"><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span></p><p><span>' + p[i].area + '</span><span class="lxr_gps" lng="' + p[i].lng+ '" lat="'+ p[i].lat+'">...</span></p></div></a></li>'
//				});
//				$("#HomeScrollUl").html(k);
//				$("#HomeScrollUl li").each(function(i,d){
//					var xing = $(this).attr("num");
//					$(this).find(".score span").slice(0,xing).css("color","#ff9d09");						
//				});
//				fun.bindOnce("#HomeViewMore",'tap',function(){
//					viewApi.go("#brand");
//				});
//				pageFun.getdistance();
//			}else{
//				mui.toast("获取数据失败");
//			}
//		});
	},
	//首页置顶店铺位置与高度
	DownScrollHeight:function(){
		$("#DownScroll").height($(window).height()-$("#indexHead").height()-$("#indexBanner").height()-$("#indexMenu").height()-$(".footer0").height()-6);
		$("#DownScroll").css("top",$("#indexHead").height()+$("#indexBanner").height()+$("#indexMenu").height());
	},
	homegetdata:function(){
		// 首页品牌获取
		Api.post(Api.home_brand,{},function(obj){
			if(obj.s){
				$('#indexPinpai dl').empty();
				var html = '';
				$.each(obj.d,function(i,d){
					html += '<dd cid="'+d.id+'"><i style="background-image:url('+d.logo+')"></i></dd>';
				});
				$('#indexPinpai dl').html(html);
				HomeBrand();
			}
		});
		function HomeBrand(){
			$('#indexPinpai dl dd').unbind('tap').on('tap',function(){
				var cid = $(this).attr('cid');
				viewApi.go('#tpl_DealerStore2',cid);
			});
		};
		//获取轮播图
		Api.post(Api.index_img,{},function(obj){
			if(obj.s){
				var u = obj.d;
				var html = '';
				html += '<div class="swiper-container swiper_home" id="indexBanner"><div class="swiper-wrapper" id="home_banner" style="font-size: 0;">';
				$.each(u,function(i,d){
					html  += '<div class="swiper-slide" cid="'+d.id+'"><img src="'+d.img+'"/></div>'; 
				});
				html += '</div><div class="swiper-pagination homeSwiperDian"></div></div>';
				
				$("#HomeMain .banner").html(html);
				
				pageFun.DownScrollHeight();
				
				var swiper22 = new Swiper('#indexBanner', {
					pagination: '.homeSwiperDian',
					autoplay:3000,
					paginationClickable: true,
					loop:true
				});
				
				swiper22.update();
				
				$('#home_banner .swiper-slide').unbind('tap').on('tap',function(){
					var cid = $(this).attr('cid');
					viewApi.go('#tpl_HomeBannerDetails',[cid]);
				});
			}
		});
		// 首页底部广告
		Api.post(Api.home_ad,{},function(obj){
			if(obj.s){
				$('#indexFujin .HomeBottomBannerImg').remove();
				var obj = obj.d;
				console.log(obj);
				var html = '';
				$.each(obj,function(i,d){
					html += '<img src="'+d.img+'" url="'+d.link+'" name="'+d.name+'" class="HomeBottomBannerImg" />';
				});
				$('#indexFujin').append(html);
				HomeBottomBannerImg();
			}else{
				mui.toast(obj.m)
			}
		});
		
		function HomeBottomBannerImg(){
			$('.HomeBottomBannerImg').unbind('tap').on("tap",function(){
				var Zurl = $(this).attr('url');
				viewApi.go('#tpl_webview',fun.base64encode(Zurl));
				
			});
		}
		// 首页 上下滚动文字
		Api.post(Api.headline,{},function(obj){
			var html = '';
			html += '<div class="swiper-container" id="indexNewsSwiper"><div class="swiper-wrapper">';
			html += '<div class="swiper-slide"><span info='+obj.d[0].id+'>'+obj.d[0].title+'</span><span info='+obj.d[1].id+'>'+obj.d[1].title+'</span></div>';
			html += '<div class="swiper-slide"><span info='+obj.d[2].id+'>'+obj.d[2].title+'</span></div>';
			html += '</div></div>';
			$('.indexNewsBox').html(html);
			var swiper222 = new Swiper('#indexNewsSwiper', {
		        paginationClickable: true,
		        autoplay:2000,
		        direction: 'vertical'
		    });
			href();
		});
		
		function href(){
			$('#indexNewsSwiper .swiper-slide span').unbind('tap').on('tap',function(){
				console.log('???')
				viewApi.go('#tpl_NewsList');
			});
		}
	},
	//发现 首页
	home:function(){
		pageFun.android_ios();
		$(".ss input").attr({"placeholder":"搜索棋牌室"});
		$(".ss input").css({'height':$('.ss').height(),"line-height":$('.ss').height()+'px'});
//		viewApi.go('#tpl_ProductPage2');
		var YD_show = fun.getCache("C");
		fun.bindOnce('#search_home','tap',function(){
			viewApi.go('#brand');
		});
//		function plusReady() {
//			var network = plus.networkinfo.getCurrentType();
//			if(network != 1){
				pageFun.GPS();
				pageFun.onepage();
				pageFun.Gpsaddr();
				var ace = fun.getCache("ace");
				if(ace){
					$(".position1 b:first-child").text(ace);
					pageFun.homebottomlist();
				}else{
					pageFun.GPS();
				}
//			}
//		}
//		if(window.plus) {
//			plusReady();
//		} else {
//			document.addEventListener("plusready", plusReady, false);
//		}
		$(".footer0").show();
		$(".footer li:nth-child(1) a p").css("color", "#ff5000");
		$("body").css("background-color","#fff");
		pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
		
		function nidianbuliao(){				
			$('body').append('<block class="blocknidianbuliao"></block>');
			$('.blocknidianbuliao').unbind('tap').on('tap',function(e){
				$('#tpl_Land').addClass('popPageShow');
				$(this).remove();
				reg();
			});
		}
		function reg(){
			$('#LandBack').unbind('tap').on("tap",function(){
				$('#tpl_Land').removeClass('popPageShow');
				$('body').append('<block class="blocknidianbuliao"></block>');
				nidianbuliao();
			});
		}
		var Is_token = fun.getCache('token');
		if(!Is_token && YD_show){
			nidianbuliao();
		}
	},
	// 首页轮播详情页
	tpl_HomeBannerDetails:function(){
		var parm = viewApi.parms;
		Api.post(Api.index_img_detail,{id:parm[0]},function(obj){
			if(obj.s){
				var title = obj.d.title != ''?obj.d.title:'暂无标题';
				var content = obj.d.content != ''?obj.d.content:'暂无详情';
				$('.HomeBannerDetailsHead h2').text(title);
				$('.HomeBannerDetailsBox').html(content);
			}else{
				mui.toast(obj.m)
			}
		})
	},
	// 定义物理返回键
	onepage:function(){
		var first = 0;
		(function(M) {
			//处理view的后退与webview后退
			var oldBack = M.back;
			M.back = function() {
				var ClickPage	= '-tpl_My-home-tpl_Admission-tpl_Mall_home-tpl_BeautyLive';
				//如果有弹出页面则先关闭弹出页面
				var Is_token = fun.getCache('token');
				var YDy = fun.getCache("C");
				function nidianbuliao(){				
					$('body').find('.blocknidianbuliao').remove();
					$('body').append('<block class="blocknidianbuliao"></block>');
					$('.blocknidianbuliao').unbind('tap').on('tap',function(e){
						$('#tpl_Land').addClass('popPageShow');
						$(this).remove();
						reg();
					});
				}
				function reg(){
					$('#LandBack').unbind('tap').on("tap",function(){
						$('#tpl_Land').removeClass('popPageShow');
						$('body').append('<block class="blocknidianbuliao"></block>');
						nidianbuliao();
					});
				}
				
				if(!Is_token && YDy){
					$('#tpl_Land').removeClass('popPageShow');
					$('body').append('<block class="blocknidianbuliao"></block>');
					nidianbuliao();
				}else{
					$('body').find('.blocknidianbuliao').remove();
					if($('.popPageShow').length>0){
						$('.popPageShow').removeClass('popPageShow');
					}else if(ClickPage.indexOf(view.currentPageId)>0){
						if (!first) {
			                first = new Date().getTime();
			                mui.toast('再按一次退出应用');
			                setTimeout(function() {
			                    first = null;
			                }, 1000);
			            } else {
			                if (new Date().getTime() - first < 2000) {
			                    plus.runtime.quit();
			                }
			            }
						return false;
					}else if (viewApi.canBack()) { //如果view可以后退，则执行view的后退
						viewApi.back();
					}else { //执行webview后退
						oldBack();
					}
				}
			}; 
		})(mui);
	},
	// 头条列表
	tpl_NewsList:function(){
		
		$('.icon-zuojiantou').unbind('tap').on('tap',function(){
			viewApi.go('#home');
		});
		(function(M){
			var oldBack = M.back;
			M.back = function() {
				mui.plusReady(function(){
					viewApi.go('#home');
				});
				return false;
			};
		})(mui);
		Api.post(Api.news_list,{cid:'86'},function(obj){
			if(obj.s){
				var html = '';
				$.each(obj.d,function(i,d){
					html += '<li cid="'+d.id+'"><p>'+d.title+'</p>';
					if(d.img && d.img.indexOf(',')){
						var img = d.img.split(',');
						$.each(img,function(ii,dd){
							html += '<i style="background-image:url('+dd+')"></i>';
						});
					}else{
						html += '<i style="background-image:url('+d.img+')"></i>';
					}
					html += '</li>';
				});
				$('main.NewsList ul').html(html);
				href();
			}else{
				mui.toast(obj.m)
			}
		});
		function href(){
			$('main.NewsList ul li').unbind('tap').on('tap',function(){
				var cid = $(this).attr('cid');
				$('#tpl_information_content').addClass('popPageShow');
				Api.post(Api.news_info,{id:cid},function(obj){
					if(obj.s){
						if(obj.d.aid === "0" || obj.d.aid === null || obj.d.aid === ""){
							$(".footer-banner").hide();
							$(".info_footer").hide();
						}else{
							$(".info_footer").show();
							$(".footer-banner").show();
							$(".footer-banner a .I_Content_banner2").attr("src",obj.d.a_url);
						}
						$('#tpl_information_content .pHead h2').text(obj.d.category);
						$(".I_Content_title").text(obj.d.title);
						$(".I_Content_time").text(obj.d.ctime);
						$(".I_Content_c").html(obj.d.content);
						$("iframe").css({'width':"100%",'height':'4rem'});
						$(".I_Content_banner2").attr("src", obj.d.a_img);
						$(".I_Content_banner2").attr("d_url", obj.d.a_url);
						$(".I_Content_banner2").addClass("weblink");
						$(".weblink").unbind('tap').on('tap',function(){
							var weburl = fun.base64encode($(this).attr('d_url'));
		//					location.href="#/webview/"+weburl;
							viewApi.go('#tpl_webview',weburl);
						});
						$('.icon-zuojiantou').unbind('tap').on('tap',function(){
							$('#tpl_information_content').removeClass('popPageShow');
							pageFun.tpl_NewsList();
						});
						MBack();
					} else {
						fun.tan(obj.m);
					}
				});
			});
		}
		function MBack(type){
			(function(M){
				var oldBack = M.back;
				M.back = function() {
					mui.plusReady(function(){
						$('#tpl_information_content').removeClass('popPageShow');
						pageFun.tpl_NewsList();
					});
					return false;
				};
			})(mui);
		}
	},
	
	homebottomlist:function(){
		var ace = fun.getCache('ace');
		var lng = fun.getCache('lng');
		var lat = fun.getCache('lat');
		Api.post(Api.home_nearby_shop,{district:ace,lng:lng,lat:lat},function(obj){
			if(obj.s){
				var html = '';
				$.each(obj.d,function(i,d){
					html += '<li><a href="#/tpl_DealerStore/'+d.id+'"><em style="background-image: url('+d.picture+');"></em><b>'+d.shop_name+'</b><u>'+d.district+'</u>';
					if(d.is_auth == 1){
						html += '<u class="RZ">会员认证V</u>';						
					}
					html += '<i>'+d.distance+'</i></a></li>';
				});
				$('#indexFujin ul').show();
				$('#indexFujin ul').html(html);
				
				if(obj.d == '' && ace == false){
					mui.toast('获取位置失败');
				}
			}else{
				mui.toast(obj.m);
			}
		});
	},
	
	
	//搜索 商品  麻将店
	search:function(){
		$('.mui-poppicker').hide();
		$("body").attr("scroll",'no');
		$("#tpl_search").css({'position':'fixed','top':'0','left':'0','bottom':'0','right':'0'})
		fun.bindOnce("#search_input",'tap',function(){
			//点击搜索框 显示搜索历史
			$(".search_History").show();
			$("#search_input").focus();
			var search = fun.getCache("search");
			$(".search_History .biao").remove();
			//循环添加 和点击历史添加到搜索框中
			$.each(search,function(i,d){
				var k = '<li class="biao"><span class="iconfont icon-biao"></span><span>'+d+'</span></li>';
				$(".search_History li:nth-last-child(1)").before(k);
			});
			$.each($(".search_History .biao"),function(){
				$(this).unbind("tap").on('tap',function(){
					var txt = $(this).find("span:nth-last-child(1)").text();
					$("#search_input").val(txt);
				});
			});
			//清空搜索历史
			fun.bindOnce(".search_History li:nth-last-child(1)",'tap',function(){
				fun.setCache("search","");
			});
		});
		$("#search_input").click();
		// 搜索框失去焦点 隐藏搜索历史
		$("#search_input").focusout(function(){
			$(".search_History").hide();
//			setTimeout(function(){ $('.mui-poppicker').show(); },500);
		});
		//点击搜索
		$("#search_input").parent(".ss").find(".click").unbind('click').click(function(){
			$(".search_History").hide();
			// 搜索历史 存进本地缓存
			var content1 = $("#search_input").val();
			var p = fun.getCache("search");
			p = p||[];
			if(content1 != ""){
				p.push(content1);
			}
			while(p.length>3){
				p.shift();
			}
			fun.setCache("search",p);
			//判断 需要执行的是 麻将店还是帖子还是商品 1是首页  2是商城 3是帖子
			if(api_k == 1){
				var lat = fun.getCache("lat");
				var lng = fun.getCache("lng");
				if(content1){
					Api.post(Api.keywode_shop,{lng:lng,lat:lat,shopname:content1},function(obj){
						if(obj.s){
							var u = obj.d;
							$(".home_asd,.search_title").remove();
							$(".mui-scroll-wrapper").hide();
							var k = '';
							if(u == ""){
								k += '<p class="search_title">没有搜索到信息</p>';
							}else{
								k += '<p class="search_title">搜索结果</p>';
							}
							k += '<div class="home home_asd" style=""><ul class="home-list brand_top">';
							$.each(u, function(i,d) {
								k += '<li class="clearfix" num="'+d.xing+'" d_id="'+d.id+'"><img src="'+d.listimg+'"><div><p class="shop_name">'+d.shopname+'</p><p class="score"><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span></p><p><span class="XL">已订'+d.order_num+'</span><span>'+d.area+'</span><span class="lxr_gps" lng="'+d.lng+'" lat="'+d.lat+'">...</span></p></div></li>';
							});
							k += '</ul></div>';
							$(".search").append(k);
							DomStyle('.home_asd');
							$(".home_asd li").unbind('tap').on('tap',function(){
								var d_id = $(this).attr("d_id");
								$(".home_asd,.search_title").remove();
								$("#search_input").val("");
								$("#tpl_search").hide();
								viewApi.go("#tpl_shop",d_id)
//								location.href="#/tpl_shop/"+d_id+"";
							});
							$(".home-list li").each(function(i,d){
								var xing = $(this).attr("num");
		    					$(this).find(".score span").slice(0,xing).css("color","#ff9d09");						
							})
							//计算距离
							pageFun.getdistance();
						}else{
							fun.tan('获取失败');
						}
					});
				}else{
					fun.tan("搜索条件不能为空")
				}
			}else if(api_k == 2){
				var key_shop = $("#search_input").val();
				if(key_shop){
					Api.post(Api.pro_list,{keyword:key_shop},function(obj){
						if(obj.s){
							var u = obj.d;
							$(".search_title,.S_MM_M").remove();
							$(".S_M_M_main").hide();
							var k = "";
							if(u == ""){
								k += '<p class="search_title">没有搜索到信息</p>';
							}else{
								k += '<p class="search_title">搜索结果</p>';
							}
							
							k += '<div class="S_M_M S_MM_M" style="padding-top:0px !important"><ul class="S_M_M_main">';
							$.each(u,function(i,d){
								k += '<li class="clearfix S_TZ" d_id="'+d.id+'"><i class="i1"style="background-image:url('+d.listimg+');" ></i><div class="text"><p>'+d.title +" "+ d.ds + '</p><p><span class="XL">销量'+d.sales+'</span><span>￥'+d.price+'</span></p></div></li>';
							});
							k += '</ul></div>'
							$(".search").append(k);
							MallHomeDomStyle('.S_M_M.S_MM_M');
							$(".S_M_M_main .S_TZ").unbind('tap').on('tap',function(){
								var d_id = $(this).attr("d_id");
								$(".search_title,.S_MM_M").remove();
								$("#search_input").val("");
								$("#tpl_search").hide();
								viewApi.go('#tpl_Product_Details',d_id);
//								location.href="#/tpl_Product_Details/"+d_id+"";
							});
						}
					});
				}else{
					fun.tan("搜索条件不能为空")
				}
			}else if(api_k == 3){
				var key_T_Z = $("#search_input").val();
				if(key_T_Z){
					Api.post(Api.tie_list,{keyword:key_T_Z},function(obj){
						if(obj.s){
							var u = obj.d;
							$(".search_title,.C_O2").remove();
							$("#bbs_tj_new").hide();
							var k = "";
							if(u == ""){
								k += '<p class="search_title">没有搜索到信息</p>';
							}else{
								k += '<p class="search_title">搜索结果</p>';
							}
							k += '<div class="C_O C_O2" style="background-color:#fff;"><div class="bbs_tj" id="bbs_tj_new">';
							$.each(u, function(i,d){
								k += '<div class="C_O_M" d_id="'+d.id+'"><div class="C_O_M_header"><i style="background-image:url('+d.img+');"></i><p>'+d.nickname+'</p> <p>'+d.ctime+'</p> </div><h3>【'+d.cname+'】'+d.title+'</h3> <div class="content"> <p>'+d.conten+'</p> <p><span class="iconfont icon-xx"></span><span>'+d.p_num+'</span></a><span class="iconfont icon-zan bbs_zan" did="'+d.id+'"></span><span class="zan" >'+d.zan+'</span>';
								if(d.status==1){
									k += '<span class="iconfont icon-del fl-right bbs_del" did="'+d.id+'" ></span>';
								}
								k += '</p></div></div>';
							});
							k += '</div></div>'
							$(".search").append(k);
							DomStyle(".C_O.C_O2");
							$("#bbs_tj_new .C_O_M").unbind('tap').on('tap',function(){
								var d_id = $(this).attr("d_id");
								$(".search_title,.C_O2").remove();
								$("#search_input").val("");
								$("#tpl_search").hide();
								viewApi.go("#T_Z1",d_id);
//								location.href="#/T_Z1/"+d_id+"";
							});
						}
					});
				}else{
					fun.tan("搜索条件不能为空")
				}
			}
			function DomStyle (DomId){
				$(DomId).css({'height':$(window).height()-$('.pHead').height()-$(".search_title").height(),'overflow':'scroll','-webkit-overflow-scrolling':'touch','padding-top':'0'})
			};
			function MallHomeDomStyle (DomId){
				$(DomId).css({'height':$(window).height()-$('.pHead').height()-$(".search_title").height(),'overflow':'scroll','-webkit-overflow-scrolling':'touch'})
			};
		});
	},
	// 品牌列表
	tpl_MoreBrands:function(){
		var wh = $(window).height() - $('.MoreBrands .title').height() - $('.MoreBrands .banner').height() - $('div.MoreBrands').height() - 13;
		
		$('.MoreBrandsList').height(wh);
		
		Api.post(Api.brand_page,{},function(obj){
			if(obj.s){
				$('.MoreBrands img').attr('src',obj.d.top_img.img);
				$('.MoreBrandsList').empty();
				var html = '';
				$.each(obj.d.list,function(i,d){
					html += '<li zid="'+d.id+'"><i style="background-image:url('+d.logo+');"></i><p>'+d.brand_name+'</p></li>';
				});
				$('.MoreBrandsList').html(html);
				clickdom();
				$.each($('.MoreBrandsList li'),function(i,d){
					if(i < 10){
						$(d).find('i').css('border-color','#ff5000');
					}
				});
			}else{
				mui.toast(obj.m)
			}
		});
		function clickdom(){
			$('.MoreBrandsList li').unbind('tap').on('tap',function(){
				var info = $(this).attr('zid');
				viewApi.go('#tpl_DealerStore2',[info]);
			})
		};
	},
	//麻将资讯
	information: function(){
		var parm = viewApi.parms;
		plp = parm[0];
		var plp2 = parm[1];
		$(".I_M_N").css("background-color","#fff");
		Api.post(Api.two_category,{id:plp},function(obj){
			if(obj.s){
				var d = obj.d;
				var plp = parm[0];
				switch (plp){
					case "1":
						$("#zixun").text("赢牌技巧");
						break;
					case "2":
						$("#zixun").text("新闻");
						break;
					case "3":
						$("#zixun").text("打牌好处");
						break;
					case "4":
						$("#zixun").text("视频吧");
						break;
					case "5":
						$("#zixun").text("今天吃什么");
						break;
				}
				$("#slide_wrapper").empty();
				$.each(d, function(i) {
					if(d[i].category == undefined) {
						return false;
					}
					var k = '<div class="swiper-slide" cid="'+d[i].id+'">' + d[i].category + '</div>';
					$("#slide_wrapper").append(k);
				});
				
				var mySwiper1 = new Swiper('#Slide_Nav',{
				  	freeMode : true,
					slidesPerView : 'auto',
			  	});
			  	
			  	//进来默认选项
				 default1 = $("#slide_wrapper div:nth-child(1)").attr("cid");
				//二级目录返回是设置页面为跳转前状态
				$.each($("#slide_wrapper .swiper-slide"),function(i,d){
					var cid = $(d).attr("cid");
					if(cid == plp2){
						$(d).addClass("border-btm2");
						default1 = cid;
					}else{
						$(d).removeClass("border-btm2");
					}
					
				})
				Api.post(Api.news_list,{cid:default1},function(obj){
					if(obj.s){
						var n = obj.d;
						$(".I_M_N .title").remove();
						var eachID = 0;
						var t = "";
						var endId = 2;
						$.each(n, function(i,d) {
//							if(i == 0 || i == eachID){
//								t += '<div class="ListMain">';
//								eachID++;
//								eachID++;
//								eachID++;
//								t += '<div class="ListMainOne" clickId="'+d.id+'" style="background:url('+d.img+')no-repeat;background-size:100% 100%;"><div class="ListMainOneTitle"><p>'+d.title+'</p></div></div>';
//							}else if(i != 0 || i != eachID){
//								t += '<div class="ListMainTow" clickId="'+d.id+'"><div class="ListMainTowLeft" style="background:url('+d.img+')no-repeat;background-size:100% 100%;"></div><div class="ListMainTowRight">'+d.title+'</div></div>';
//								if(i == 2 || i == endId){
//									endId++;
//									endId++;
//									endId++;
//									t += '</div>';
//								}
//							}
							t += '<div class="title title_wx" clickid="' + n[i].id + '" aid=' + n[i].aid + ' ><p class="content_title">'+d.title+'</p><p class="content_time">'+d.ctime+'</p><p class="content_banner"><img src="'+d.img+'"/></p><p class="content_Hyperlink">查看全文</p></div>';
						});
						$("#information_container").html(t);
						pageFun.initIMN_Click();
					} else {
						fun.tan("获取失败");
					}
				});
				
				if(plp2<=5){
					$(".swiper-wrapper div:nth-child(1)").addClass("border-btm2");
				}
				$(".swiper-wrapper div").unbind('tap').on('tap',function() {
					$(".swiper-wrapper div").removeClass("border-btm2");
					$(this).addClass("border-btm2");
					var cid = $(this).attr("cid");
					Api.post(Api.news_list,{cid:cid},function(obj){
						if(obj.s){
							var n = obj.d;
							$(".I_M_N .title").remove();
							var t = "";
							$.each(n, function(i,d) {
//								var t = '<div class="title" clickid="' + n[i].id + '" aid=' + n[i].aid + '><div class="btm clearfix"><img src="' + n[i].img + '" width="100%"/><p><span>' + n[i].title + '</span><br /><span class="ZX_ctime">' + n[i].ctime + '</span><br /><span>' + n[i].n_con + '</span></p></div></div>';
								t += '<div class="title title_wx" clickid="' + n[i].id + '" aid=' + n[i].aid + ' ><p class="content_title">'+d.title+'</p><p class="content_time">'+d.ctime+'</p><p class="content_banner"><img src="'+d.img+'"/></p><p class="content_Hyperlink">查看全文</p></div>';
//								$("#information_container").append(t);
							});
//							var eachID = 0;
//							var endId = 2;
//							$.each(n, function(i,d) {
//								if(i == 0 || i == eachID){
//									t += '<div class="ListMain">';
//									eachID++;
//									eachID++;
//									eachID++;
//									t += '<div class="ListMainOne" clickId="'+d.id+'" style="background:url('+d.img+')no-repeat;background-size:100% 100%;"><div class="ListMainOneTitle"><p>'+d.title+'</p></div></div>';
//								}else if(i != 0 || i != eachID){
//									t += '<div class="ListMainTow" clickId="'+d.id+'"><div class="ListMainTowLeft" style="background:url('+d.img+')no-repeat;background-size:100% 100%;"></div><div class="ListMainTowRight">'+d.title+'</div></div>';
//									
//									if(i == 2 || i == endId){
//										endId++;
//										endId++;
//										endId++;
//										t += '</div>';
//									}
//								}
//							});
							$("#information_container").html(t);
							pageFun.initIMN_Click();
						} else {
							fun.tan("获取失败2");
						}
					});
				});
			} else {
				fun.tan("获取失败");
			}
		});
	},
	initIMN_Click: function(){
		$(".title_wx").unbind('tap').on('tap',function(){
			clickid2 = $(this).attr("clickid");
			clickid3 = $("#slide_wrapper .border-btm2").attr("cid");
			$("#tpl_information_content").addClass("popPageShow");
			pageFun.information_content1();
		})
//		$(".ListMainOne,.ListMainTow").unbind('tap').on('tap',function(){
//			clickid2 = $(this).attr("clickid");
//			clickid3 = $("#slide_wrapper .border-btm2").attr("cid");
//			$("#tpl_information_content").addClass("popPageShow");
//			pageFun.information_content1();
//		})
	},
	//麻将资讯内容
	information_content1: function(){
		$("#informationContent").scrollTop(0);
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			$("#tpl_information_content").removeClass("popPageShow");
			fun.bindOnce('.icon-zuojiantou','tap',function(){
				viewApi.back();
			})
		})
		$("#informationContent").height($(window).height()-$('.header_1').height()).addClass('scroll')
		Api.post(Api.two_category,{id:plp},function(obj){
			if(obj.s){
				var u = obj.d;
				$.each(u,function(i,d){
					if(clickid3 == d.id){
						$("#tpl_information_content h2").text(d.category);
					}
				})
			}
		});
		Api.post(Api.news_info,{id:clickid2},function(obj){
			if(obj.s){
				if(obj.d.aid === "0" || obj.d.aid === null || obj.d.aid === ""){
					$(".footer-banner").hide();
					$(".info_footer").hide();
				}else{
					$(".info_footer").show();
					$(".footer-banner").show();
					$(".footer-banner a .I_Content_banner2").attr("src",obj.d.a_url);
				}
				$(".I_Content_title").text(obj.d.title);
				$(".I_Content_time").text(obj.d.ctime);
				$(".I_Content_c").html(obj.d.content);
				$("iframe").css({'width':"100%",'height':'4rem'});
				$(".I_Content_banner2").attr("src", obj.d.a_img);
				$(".I_Content_banner2").attr("d_url", obj.d.a_url);
				$(".I_Content_banner2").addClass("weblink");
				$(".weblink").unbind('tap').on('tap',function(){
					var weburl = fun.base64encode($(this).attr('d_url'));
//					location.href="#/webview/"+weburl;
					viewApi.go('#tpl_webview',weburl);
				});
			} else {
				fun.tan(obj.m);
			}
		});
	},

	//购物车
	Shopping_Cart: function() {
		pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
		var token = fun.getCache('token');
		if(!token){
			setTimeout(function(){
				$(".mui-popup-buttons span:nth-child(1)").css("color",'#444');
			},100)
			var btnArray = ['否', '是'];
			mui.confirm('是否登录？', '未登录', btnArray, function(e) {
				if (e.index == 1) {
					$("#tpl_Land").addClass('popPageShow');
					pageFun.login();
				} else {
					
				}
			})
		}
		$("#CartMain").css({"height":$(window).height()-$('.pHead').height()-$("#Shopping_Cart .Settlement").height()-$(".footer0").height()-8,'overflow-y':'scroll','-webkit-overflow-scrolling':'touch','padding-bottom':'0'})
		$(".footer0").show();
//		$("#Shopping_Cart_id").find("header").css("z-index","5");
		function carlist(){
			Api.post(Api.car_list, {}, function(obj) {
				if(obj.s) {
					$('.lxr_cart_show').empty();
					var html = "";
					$.each(obj.d, function(i, d) {
						html += '<li class="content clearfix" did="' + d.id + '"><i class="iconfont Choice" ></i><img src="' + d.listimg + '" class="tu"/><p class="name">' + d.ds + '</p><p class="class">选择分类：' + d.attr_name + '</p><p><span class="Price" pick="' + (Number(d.price) + Number(d.attr_dif)).toFixed(2) + '">￥' + (Number(d.price) + Number(d.attr_dif)).toFixed(2) + '</span>';
						html += '<span class="fl-right number "  pnum="' + d.attr_num + '"><button class="J_J carLXRPZ cat_del mui-btn mui-btn-numbox-minus" type="button">-</button>';
						if(Number(d.attr_num) < Number(d.num)) {
							html += '<input type="number" value="' + d.attr_num + '"  class="mui-input-numbox car_cum"  />';
							
						} else {
							html += '<input type="number" value="' + d.num + '"  class="mui-input-numbox car_cum"  />';
						}
						html += '<button class="J_J cat_add carLXR mui-btn mui-btn-numbox-plus" type="button">+</button></span></p></li>';
					})
					$('.lxr_cart_show').append(html);
					$("#CartMain .car_cum").blur(function(){
						var inVla = $('#CartMain .car_cum').val();
						if(inVla == '0'){
							$('#CartMain .car_cum').val('1');
						}
					})
					check();
					pick();
				}
			});
			$('.lxr_settlement').unbind('tap').on('tap',function() {
				var idarr = [];
				$('.lxr_check').each(function(i) {
					idarr.push($(this).attr('did'));
				})
				var id = idarr.join("_");
				var canbak = upnum();
				if(canbak == false) {
					fun.tan("库存异常");
					return false;
				}
				if(id != "") {
					viewApi.go("#tpl_Confirm_Order",[id]);
				} else {
					fun.tan("请选择要结算的商品");
				}

			});
		}
		carlist();

		function upnum() {
			var numarr = [];

			$('.lxr_cart_show li').each(function(i) {
				numarr.push($(this).attr('did') + ":" + $(this).find("input").val());
			})
			var num = numarr.join("_");
			Api.post(Api.car_upnum,{data:num},function(obj){
				if(obj.s){
					return true;
				} else {
					return false;
				}
			})

		}

		function check() {

			$(".carLXRPZ").unbind('tap').on('tap',function() {
				var q = $(this).siblings('.car_cum').val();
				if(q == '0'){
					return false;
				}
				if(q > 1) {
					q--;
				}else{
					fun.tan("数量不能低于1");
				}
				$(this).siblings('.car_cum').val(q);
				pick();
			});
			$(".catLXR").unbind('tap').on('tap',function() {
				var q = $(this).siblings('.car_cum').val();
				var num = parseInt($(this).parents('.number').attr("pnum"));
				if(q < num) {
					q++;
				} else {
					fun.tan("库存不足");
				}
				$(this).siblings('.car_cum').val(q);
				pick();
			});
			$(".Choice").unbind('tap').on('tap',function() {
				if(!$(this).hasClass("icon-duigou")) {
					$(this).addClass("icon-duigou");
					$(this).parent('li').addClass("lxr_check");
				} else {
					$(this).removeClass("icon-duigou");
					$(this).parent('li').removeClass("lxr_check");
				}	
			$('.quanxuan').removeClass("icon-duigou").css({"border":"#dadada 2px solid"});
			pick();
			});
			
			$(".quanxuan").unbind('click').click(function() {
				if(!$(this).hasClass("icon-duigou")) {
					$(".Choice").addClass("icon-duigou");
					$(".Choice").parent('li').addClass("lxr_check");
					$(this).addClass("icon-duigou").css({"border":"#FF5000 2px solid","color":"#FF5000"});;	
				}else{
					$(".Choice").removeClass("icon-duigou");
					$(".Choice").parent('li').removeClass("lxr_check");
					$(this).removeClass("icon-duigou").css({"border":"#dadada 2px solid"});	
				}
				pick();
			})
		}

		function pick() {
			var conn = 0;
			$('.lxr_check').each(function(i) {
				var c = $(this).find(".Price").attr('pick');
				var n = $(this).find("input").val();
				var cun = c * n;
				conn += cun;
			});

			$('.lxr_pcont').text("￥" + conn.toFixed(2));
		}

		$('.lxr_delcar').unbind('tap').on('tap',function() {
			var cidarr = [];
			$('.lxr_check').each(function(i) {
				var cid = $(this).attr('did');
				cidarr.push(cid);
			});
			if(cidarr.length < 1){
				fun.tan("请选择要删除的商品");
				return false;
			}
			Api.post(Api.del_car,{listid:cidarr},function(obj){
				if(obj.s){
					carlist();
					check();
				}
			});

		})

	},
	//关于我们  Miao 11-29
	About_us: function() {
		$("html,body,.mypage,.container,.About_us,.About_us2").css("height", "100%");
		$(".About_us,.About_us2").css("background-color", "#fff");
		Api.post(Api.about,{}, function(obj) {
			if(obj.s) {
				$("#About_us_text").empty();
				$("#About_us_text").append(obj.d);
			}
		});
	},
	//软件介绍  Miao 11-29
	About_us2: function() {
		$("html,body,.mypage,.container,.About_us2").css("height", "100%");
		$(".About_us2").css("background-color", "#fff");
		Api.post(Api.introduce, {}, function(obj) {
			if(obj.s) {
				$("#About_us2_text").empty();
				$("#About_us2_text").append(obj.d);
			}
		});
	},
	//群资料修改   miao 2016-12-15
	qun: function() {
		var parm = viewApi.parms;
		plp = parm[0];
		$(".Chat-header").hide();
		$('.editpage').unbind('tap').on('tap',function() {
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);
		});
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$("#group_img_xiu").show();
				$("#group_img_xiu").css("background-image", 'url(' + res.target.result + ')');
				$("#group_img_xiu").attr("imgdata", res.target.result);
			}
			fr.readAsDataURL(file);
		});
		$("#group_xiu").unbind('tap').on('tap',function() {
			var name = $("#group_name_xiu").find(".content").text();
			var xuzhi = $(".xuzhi").find("textarea").val();
			var nameL = name.length;
			var imgdata = $("#group_img_xiu").attr("imgdata");
			if(nameL < 10 && name != "" && name != null && name != undefined){
				hx.post(hx.around,{id:3,group_num:plp,groupname:name,description:xuzhi,img:imgdata},function(obj){
					if(obj.s){
						viewApi.back();
					}
				});
			} else {
				fun.tan("群名称最大长度为10");
			}
		});
	},
	//群组
	Group: function() {
		$(".footer9").show();
		$(".footer9 li:nth-child(2) a p").css("color", "#ff5000");
//		$(".Group-main li").click(function() {
//			if($(this).attr("qid")) {
//				location.href = "#/tpl_FS_XX/" + $(this).attr("qid") + "";
//			}
//		});
		hx.post(hx.around,{id:1},function(obj){
			if(obj.s && obj.d  != "" && obj.d != null && obj.d != undefined){
				var l = obj.d;
				$("#Official_group").empty();
				var k = ''
				$.each(l, function(i, d) {
					k += '<a href="#/tpl_Group_chat/' + d.groupid + '/' + encodeURI(d.groupname) + '"><li class="clearfix" qid="' + d.groupid + '"><i class="i1" style="background:url(' + d.img + ');background-size:100% 100%;"></i><span>' + d.groupname + '</span></li></a>';
				});
				$("#Official_group").html(k);
			}
		});
	},
	//商城首页
	Mall_home:function(){
		$(".footer li:nth-child(3) a p").css("color","#ff5000");
		pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
		$("#MallHomeSearch").css({'height':$('.ss').height(),"line-height":$('.ss').height()+'px'});
		Api.post(Api.shop_index,{},function(obj){
			if(obj.s){
				var p = obj.d;
				//商城首页 轮播图
				var k = "";
				k += '<div class="swiper-container MallHomeCarousel" id="MallHomeCarousel" style="font-size: 0;height: 2rem;"><div class="swiper-wrapper">'
				
				$.each(p.img,function(i,d){
					k += '<div class="swiper-slide"><img src="'+d.img+'" d_url="'+d.goods_id+'"/></div>';
				});
				k += '</div><div class="swiper-pagination" style="text-align:right;" id="MallHomeCarouselPagintion"></div></div>';
				
				$(".MallHome .Mallbanner").html(k);
				
				var MallHome = new Swiper('#MallHomeCarousel', {
					pagination: '#MallHomeCarouselPagintion',
					paginationClickable: true,
					loop:true
				});
				MallHome.update();
				$("#MallHomeCarousel img").unbind('tap').on('tap',function(){
					var Turl = $(this).attr("d_url");
					viewApi.go('#tpl_Product_Details',[Turl]);
//					viewApi.go('#tpl_webview',fun.base64encode(Turl));
				});
				//商城首页 导航
				var nav = "";
				$.each(p.category,function(i,d){
					nav += '<li navId="'+d.id+'"><i class="nav'+i+'" style="background:url('+d.cate_img+');background-size:100% 100%;"></i><span>'+d.category+'</span></li>';
				});
				$("#MallHomeNav").html(nav);
				$("#MallHomeNav li").unbind('tap').on('tap',function(){
					var MallHomeNavId = $(this).attr('navId');
					viewApi.go("#tpl_Shopping_Mall",MallHomeNavId);
				});
				//商城广告
//				$(".MallHomeBanner").find('img').attr({'src':p.advertising.img[0],'d_url':p.advertising.url});
//				$(".MallHomeBanner img").unbind('tap').on('tap',function(){
//					var d_url = $(this).attr("d_url");
//					viewApi.go('#tpl_webview',fun.base64encode(d_url));
//				});
				
				//热门商品
				var HotMain = "";
				$("#MallHomeHot ul").empty();
				$.each(p.hot,function(i,d){
					HotMain += '<li ShopId="'+d.id+'"><img src="'+d.listimg+'"/><p class="PopularCommodityContentTitle">'+d.title+'</p><p class="PopularCommodityContentPrice clearfix"><span class="PopularCommodityPrice">￥'+d.price+'.00</span><span class="PopularCommoditySV">销量'+d.sales+'</span></p></li>';
				});
				$("#MallHomeHot ul").html(HotMain);
				$("#MallHomeHot").height($(window).height()-$("#MallHomeNav , #MallHomeCarousel , .MallHomeBanner , .PopularCommodity").height()-66);
				//热门商品 点击跳转
				$('#MallHomeHot ul li').unbind('tap').on('tap',function(){
					var ShopId = $(this).attr('ShopId');
					viewApi.go("#tpl_Product_Details",ShopId);
				});
			}
		});
		$(".ss input").attr({"placeholder":"搜索商品"});
		
		$("#MallHomeSearch").parents('.ss').unbind("click").click(function(){
			$("#tpl_search").addClass('popPageShow');
			$(".ss input").attr({"placeholder":"搜索商品"});
			fun.bindOnce('.icon-zuojiantou','tap',function(){
				$("#search_input").val("");
				$("#tpl_search").removeClass('popPageShow');
				$('.popPageShow').removeClass('popPageShow');
			});
			api_k = 2;
			pageFun.search();
		});
	},
	//商城
	Shopping_Mall: function() {
		pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
		$(".footer li:nth-child(3) a p").css("color", "#ff5000");
		$(".footer0").show();
		
		
		var parm = viewApi.parms;
		var plp = parm[0];
		if(plp == '3'||plp == '4'||plp == '5'||plp == '6'){
			ShoppingMallTemporaryPLP = plp;
			shop_info(ShoppingMallTemporaryPLP);
		}else{
			shop_info(ShoppingMallTemporaryPLP);
		}
		$(".S_M_M_main").show();
		$(".S_M_M_header li").unbind('tap').on('tap',function(){
			var type = $(this).attr("type");
			shop_info(ShoppingMallTemporaryPLP);
		});
//		$('#ShoppingMall li:nth-child(1)').addClass('border-btm');
		function shop_info(TemporaryPLP){
			var type=$('.border-btm').attr('type');
			Api.post(Api.pro_list,{type:type,cid:TemporaryPLP},function(obj){
				if(obj.s){
					var data=obj.d;	
					$(".S_M_M_main").empty();
					var html="";
					$.each(data,function(i,d){				
						html+='<li class="clearfix"><a href="#/tpl_Product_Details/'+d.id+'"><i class="i1"style="background-image:url('+d.listimg+');" ></i><div class="text"><p>'+d.title +" "+ d.ds + '</p><p><span class="XL">销量'+d.sales+'</span><span>￥'+d.price+'</span></p></div></a></li>';	
					})
					$(".S_M_M_main").append(html);
				}
			});
		}
		$("#search_Shopping_Mall").parents('.ss').unbind("click").click(function(){
			$("#tpl_search").addClass('popPageShow');
			$(".ss input").attr({"placeholder":"搜索商品"});
			fun.bindOnce('.icon-zuojiantou','tap',function(){
				$("#search_input").val("");
				$(".search_title,.S_MM_M").remove();
				$("#tpl_search").removeClass('popPageShow');
			});
			api_k = 2;
			pageFun.search();
		});
	},
	
	
	initLBT:function(boxId,dataList){
		$('#'+boxId).empty();
		$('#'+boxId).html('<div class="swiper-container swiper_'+boxId+'"><div class="swiper-wrapper SwiperImg_'+boxId+'" style="font-size: 0;"></div><div class="swiper-pagination SwiperSpot_'+boxId+'"></div></div>');
		var html = '';
		$.each(dataList,function(i,d){
			html += '<div class="swiper-slide"><img src="' + d + '"></div>';
		});
		$('.SwiperImg_'+boxId).html(html);
		pageFun.LBT('.swiper_'+boxId,'.SwiperSpot_'+boxId);
	},
	
	//商品详情
	Product_Details: function() {
		var parm = viewApi.parms;
		if(parm.length<1) return false;
		var id = parm[0];
		//$('#detialBannerBox').empty();
		//$('#detialBannerBox').html('<div class="swiper-container swiper_P_D"><div class="swiper-wrapper PD_swiper" style="font-size: 0;"></div><div class="swiper-pagination PDMSwiper"></div></div>');
		Api.post(Api.pro_info,{id:id},function(obj){
			if(obj.s){
				var data=obj.d;
				/*$('.swiper-wrapper').empty();
				var htmls = "";
				$.each(data.showimg, function(i, d) {
					htmls += '<div class="swiper-slide"><img src="' + d + '"></div>';
				});
				$('.swiper-wrapper').html(htmls);
				pageFun.LBT('.swiper_P_D','.PDMSwiper');*/
				
				pageFun.initLBT('detialBannerBox',data.showimg);
				
				$('.describe').text(data.ds);
				$('.J_G span:first').text("￥" + data.price);
				$('.XL').text("销量" + data.sales);
				$('.shop_content').empty();
				$('.shop_content').append(data.content);
				$('.shop_img').css({"background-image":'url('+data.listimg+')'});
				$('.shop_pic').text("￥"+data.price);
				$('#Eject_class').empty();
				$('.btn').attr('pid', data.id);
				var htmlb = "";
				htmlb += '<li >颜色分类</li>';
				$.each(data.pro_attr, function(i, d) {
					htmlb += '<li dif="' + d.dif + '" did="' + d.id + '" panum="' + d.num + '">' + d.name + '</li>';
				});
				var k = "";
				$.each(data.pinglun_info,function(i,d){
					k += '<div class="block2 clearfix"><div class="left"><p style="padding-top:0.2rem">'+d.nickname+'</p><p style="padding-top:0.2rem">'+d.content+'</p></div><p class="fl-left" style="padding-top:0.2rem"><span style="letter-spacing: 0.02rem;">'+d.ctime+'</span></p>';
					if(d.ping_img != ""){
						k += '<p class="fl-left img" style="">';
						$.each(d.ping_img,function(ii,dd){
							k += '<i style="background-image:url('+dd+')"></i>';
						})
						k += '</p>';
					}
					k += '</div>';
				});
				$("#Commodity_Evaluta").append(k);
				$("#Commodity_Evaluta").find(".block2:nth-last-child(1)").css("border-bottom","none");
				
				$("#Details").height($(window).height()-$(".header_1").height()).addClass('scroll');
				
				$('#Eject_class').append(htmlb);
				$(".G_W_C_Eject .main li").unbind('click').click(function() {
					$('.G_W_C_Eject .main').css("border", "0px");
					$(".G_W_C_Eject .main li").removeClass("cli");
					$(this).addClass("cli");
					var panum = $(this).attr("panum");
					$('.number').attr('num', panum);
					var t = $('.cli').attr("dif");
					$('.shop_pic').text("￥" + (parseFloat(data.price) + parseFloat(t))).attr("pic", (parseFloat(data.price) + parseFloat(t)));
					jg();
				});

			}
		});
		$("#lxr_pdel").unbind('tap').on('tap',function() {
			if($('.G_W_C_Eject .main li.cli').length < 1) {
				$('.G_W_C_Eject .main').css("border", "solid 1px red");
				return false;
			}
			var q = $("#in").val();
 			if(q == '0'){
				return false;
			}
			var num = Number($("#purchaseNumber").attr("num"));
			
			if(q > 1) {
				q--;
			}else{
				fun.tan("数量不能低于1")
			}

			$("#in").val(q);
			jg();
		});
		
		$("#in").blur(function(){
			var inVla = $('#in').val();
			if(inVla == '0'){
				$('#in').val('1');
			}
		})
		$("#lxr_padd").unbind('tap').on('tap',function() {
			if($('.G_W_C_Eject .main li.cli').length < 1) {
				$('.G_W_C_Eject .main').css("border", "solid 1px red");
				return false;
			}
			var q = $("#in").val();
			if(q == '0'){
				return false;
			}
			var numXX = $("#purchaseNumber").attr("num");
			if(q < numXX) {
				q++
			} else {
				fun.tan("库存不足");
			}
			$("#in").val(q);
			jg();
		});

		function jg() {
			var sop = $('.shop_pic').attr("pic");
			var q = $("#in").val();
			var jg = sop * q;
			$('.shop_pic').text("￥" + jg.toFixed(2));
		}

		$(".P_D_footer li,.G_M").unbind('click').click(function() {
			var token = fun.getCache('token');
			if(token){
				var type = $(this).attr('type');
				$('.btn').attr("type", type);
				$(".G_W_C_Eject,.rgba").show();
			}else{
				mui.toast('请先登录');
			}
		});
		$(".icon-guanbi").unbind('click').click(function() {
			$(".G_W_C_Eject,.rgba").hide();
			$("#in").val(1);
			$(".main li.cli").removeClass("cli")
			$('.btn').attr("type", "nul");
		});
		$('.btn').unbind('click').click(function() {
			var type = $(this).attr("type");
			if(type == "nul") {
				$(".G_W_C_Eject,.rgba").hide();
				return false;
			}
			if($('.G_W_C_Eject .main li.cli').length < 1) {
				$('.G_W_C_Eject .main').css("border", "solid 1px red");
				return false;
			}
			if(type=="gwc"){
				var Number = $("#in").val();
				var Stock = $('#purchaseNumber').attr('num');
				var id=$('.btn').attr('pid');
				var aid=$('.cli').attr("did");;
				var num=$("#in").val();
				Api.post(Api.buy_car,{id:id,aid:aid,num:num},function(obj){
					if(obj.s){
						fun.tan("已加入购物车")
						$(".G_W_C_Eject,.rgba").hide();
						$('#in').val(1);
						$('.cli').removeClass('cli');
					}
				});
			}
			if(type=="gm"){
				var Number = $("#in").val();
				var Stock = $('#purchaseNumber').attr('num');
				var id=$('.btn').attr('pid');
				var aid=$('.cli').attr("did");;
				var num=$("#in").val();
				Api.post(Api.buy_car,{id:id,aid:aid,num:num},function(obj){
					if(obj.s){		
						viewApi.go('#tpl_Confirm_Order',[obj.d,num]);
						$('#in').val(1);
						$('.cli').removeClass('cli');
					}
				});
			}
		});
		
		fun.bindOnce(".pHead .icon-car",'tap',function(){
			viewApi.go('#Shopping_Cart_page');
		});
	},
	//社区
	Community:function(){
		pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
		$(".footer0").show();
	
		$("#Community_list").parents("body").addClass("body_height");

		$("#CommunityContent").height($(window).height()-$('#CommunityHeader').height()-$('.footer0').height()-$('.S_M_M_header.Community-tab.clearfix').height()-20).addClass("scroll");
		$(".footer li:nth-child(2) a p").css("color", "#ff5000");
		Api.post(Api.userinfo,{},function(obj){
			if(obj.s){
				$('.Community').css({"background-image":'url('+obj.d.img+')'});
			}
		});
		cindex();
		function cindex(){
			var i=$('.border-btm').attr('type');
			Api.post(Api.tie_list,{type:i},function(obj){
				if(obj.s){
					var data=obj.d;
					var html='';
					$(".bbs_tj").empty();
					$.each(data, function(i,d){
						html+='<div class="C_O_M"> <div class="C_O_M_header"> <i style="background-image:url('+d.img+');"></i> <p>'+d.nickname+'</p> <p>'+d.ctime+'</p> </div><a href="#/tpl_T_Z1/'+d.id+'"><h3>【'+d.cname+'】'+d.title+'</h3> <div class="content"> <p>'+d.conten+'</p> <p><a href="#/tpl_T_Z1/'+d.id+'"><span class="iconfont icon-xx"></span><span>'+d.p_num+'</span></a>';
						if(d.zan_status == 1){
							html += '<span class="iconfont icon-zan bbs_zan" did="'+d.id+'" style="color:#ff5000;"></span><span class="zan" style="color:#ff5000;">'+d.zan+'</span>';
						}else{
							html += '<span class="iconfont icon-zan bbs_zan" did="'+d.id+'"></span><span class="zan" >'+d.zan+'</span>';
						}
						if(d.status==1){
							html+='<span class="iconfont icon-del fl-right bbs_del" did="'+d.id+'" ></span>';
						}
						html+='</p></div></a></div>';
					});
					$(".bbs_tj").append(html);
					ck();
				}
			});
		};
		function ck(){
			$(".bbs_zan").unbind('tap').on('tap',function(){
			var id=$(this).attr('did');
			Api.post(Api.tie_zan,{bbs_id:id},function(obj){
				if(obj.s){
					cindex();
				}else{
					if(obj.m == 'Token does not exist,Please login'){
						fun.tan('请先登录');
					}else{
						fun.tan(obj.m);
					}
				}
			})
		});
		$(".bbs_del").unbind('tap').on('tap',function(){
			var id=$(this).attr('did');
				var btnArray = ['取消', '确认'];
				mui.confirm('是否确认删除？', '您好', btnArray, function(e) {
					if (e.index == 1){
						Api.post(Api.tie_del,{id:id},function(obj){
						if(obj.s){
							fun.tan("删除成功");
							cindex();
						}
					})
				}
			});
		});
		}
		$(".ss input").attr({"placeholder":"搜索帖子"});
		
		//搜索
		$("#keyword").unbind('click').click(function(){
			
			$("#tpl_search").addClass('popPageShow');
			$("#Community_list").hide();
//			$("#search_input").val(content);
			$("#search_input").attr("placeholder","搜索帖子");
			fun.bindOnce('.icon-zuojiantou','tap',function(){
				$(".search_title,.C_O2").remove();
				$("#tpl_search").removeClass('popPageShow');
				$("#Community_list").show();
			});
			api_k = 3;
			pageFun.search();
		})
		function bk() {
			Api.post(Api.tie_model, {}, function(obj) {
				if(obj.s) {
					$('#bkCategoryList').empty();
					var html = '';
					$.each(obj.d, function(i, d) {
						html += '<li  class="bk_li"><a href="#/tpl_bkl/' + d.id + '"><p style="background-image:url(' + d.cate_img + ');" did="' + d.id + '"></p><p did="' + d.id + '">' + d.category + '</p></a></li>';
					});
					$('#bkCategoryList').html(html); 
					$('#bkCategoryList a').unbind('click').click(function(e){});
					fun.bindLinkToRouter('#bkCategoryList a');
				}
			});
		}
		$(".bbs_tj").css("background-color",'#f4f4f4');
		 
		$(".Community-tab li").unbind('tap').on('tap',function() {
			$(".C_O_M,.bk").hide();
			var i = $(this).attr("tab");
			$(i).show();
			if($(this).attr("tab") == ".bk") {
				bk();
				$(".bbs_content_container").hide();
				$("html,body,.mypage,.container,.Community1,.page").css("height", "100%");
				$(".Community,.page").css("background-color", "#fff");
			} else {
				cindex();
				$(".bbs_content_container").show();
				$("html,body,.mypage,.container,.Community1,.page").css("height", "auto");
				$(".Community,.page").css("background-color", " ");
			}
		});
	},
	//板块
	bk:function(){
		var parm = viewApi.parms;
		$('.bbs_tj').height($(window).height()-$('.header_1').height()-6).addClass('scroll');
		Api.post(Api.tie_list,{cid:parm[0]},function(obj){
			if(obj.s){
				var data=obj.d;
				var html='';
				$('#T_Z_Tile').text(obj.n);
				$(".bbs_tj").empty();
				$.each(data, function(i,d){
					html+='<div class="C_O_M"> <div class="C_O_M_header"> <i style="background-image:url('+d.img+');"></i> <p>'+d.nickname+'</p> <p>'+d.ctime+'</p> </div><a href="#/tpl_T_Z1/'+d.id+'/bkl"><h3>【'+d.cname+'】'+d.title+'</h3> <div class="content"> <p>'+d.conten+'</p> <p><a href="#/tpl_T_Z1/'+d.id+'"><span class="iconfont icon-xx"></span><span>'+d.p_num+'</span></a>';
					if(d.zan_status == 1){
						html += '<span class="iconfont icon-zan bbs_zan" did="'+d.id+'" style="color:#ff5000;"></span><span class="zan" style="color:#ff5000;">'+d.zan+'</span>';
					}else{
						html += '<span class="iconfont icon-zan bbs_zan" did="'+d.id+'"></span><span class="zan" >'+d.zan+'</span>';
					}
					if(d.status==1){
						html+='<span class="iconfont icon-del fl-right bbs_del" did="'+d.id+'" ></span>';
					}
					html+='</p></div></a></div>';
				});
				$(".bbs_tj").append(html);
				$(".S_M_M").removeClass("bk_padding_top");
				$(".bbs_tj .C_O_M:nth-last-child(1)").css("margin-bottom",'0.1rem');
			};
		});
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			viewApi.go("#community");
		})
	},
	//引导页
	YD: function() {
		$("html,body").css("height", "100%");
		$(".pBody").addClass("yangshi2");
		$(".rgba").hide();
		var swiper = new Swiper('.swiper-container', {
			pagination: '.swiper-pagination',
			paginationClickable: true,
			onSlideChangeStart: function(swiper) {
				if(swiper.activeIndex > 1) {
					$(".yangshi3").hide();
					$('.Y-btn').show();
				} else if(swiper.activeIndex < 2) {
					$(".yangshi3").show();
					$('.Y-btn').hide();
				}
			}
		});
		$(".Y-btn").unbind('touchend').on('touchend',function(e) {
			localStorage.C = "1";
			$("#tpl_YD").hide(200);
			$(".pBody").removeClass("yangshi2");
			pageFun.home();
			e.preventDefault();
		});
	},
	//帖子
	T_Z1: function() {
		var parm = viewApi.parms;
		var	id = parm[0];
		$(".TZ").css("height",$(window).innerHeight()+'px').css("background-color","#fff");
		$('#PostContentMainStyle').height($(window).height()-$('.header_1,.TZ_Footer').height()-56).addClass('scroll');
		Api.post(Api.tie_info,{id:id},function(obj){
			if(obj.s){
				var d=obj.d;
				if(parm[1] == "bkl"){
					fun.bindOnce('.icon-zuojiantou','tap',function(){
						viewApi.go('#tpl_bkl',[d.data.cid]);
					});
				}
				$('.user_img').css("background-image",'url('+d.data.user_img+')');
				$('.user_name').text(d.data.user);
				$('.lxr_ctime').text(d.data.c_time);
				$('.lxr_zhan').text(d.data.zan);
				$('.lxr_pnum').text(d.data.p_num);
				$('.lxr_title').text('【' + d.data.c_name + '】' + d.data.title);
				$('.lxr_bk').text(d.data.c_name);
				$("#TZPre").empty();
				$('.bbs_content').html(d.data.conten);
				var PreImg = '';
				var num = d.data.img.length;
				$.each(d.data.img,function(i,d){
					if(num == 1){
						PreImg += '<img src="'+d+'" width="100%">';
					}else if(num == 2 ){
						PreImg += '<img src="'+d+'" style="float:left;margin-right:1.5%;width:2.8rem;height:2.8rem;">';
					}else if(num >= 3){
						PreImg += '<img src="'+d+'" style="float:left;margin-right:1.5%; width:1.8rem;height:1.8rem;">';
					}
				});
				$("#TZPre").html(PreImg);
				$(".bbs_list").attr('id', d.data.id);
				$("#tz_pl").empty();
				var tpl = '<p class="PurchaseNotice"><span class="iconfont icon-pingjia"></span><span>评价</span></p>';
				$.each(d.p_data, function(ii, dd) {
					tpl += '<div class="block2 clearfix"><div class="clearfix"><p class="">' + dd.nickname + '</p>';
//					tpl += '<p class="score clearfix"></p>';
					tpl += '<p><span style="letter-spacing: 0.02rem;">' + dd.ctime + '</span></p>';
					tpl += '<p>' + dd.content + '</p>';
					tpl += '</div>';
					tpl += '<p class="fl-left img" style="">';
					if(dd.content_img.length > 1){
						$.each(dd.content_img, function(iii,ddd) {
							tpl += '<i style="background-image:url(' + ddd + ')"></i>';
						});							
					}else{}
					tpl += '</p>';
					tpl += '</div>';
				});
				$("#tz_pl").html(tpl);
			}
		});
		$(".icon-zan , #zt_content_zan").unbind('click').click(function(){
			var i = $("#zt_content_zan").text();
			Api.post(Api.tie_zan,{bbs_id:id},function(obj){
				if(obj.s){
					i++;
					$("#zt_content_zan").text(i);
				}else{
					if(obj.m == 'Token does not exist,Please login'){
						fun.tan('请先登录');
					}else{
						fun.tan(obj.m);
					}
				}
			})
		});
		$("#PostPostImgBlock .tu").remove();
		$('.upfile').unbind('change').on('change',function() {
			if($('#PostPostImgBlock .tu').length<3){
				var _this = this;
				var file = document.getElementById($(this).attr('id')).files[0];
				var fr = new FileReader();
				fr.onload = function(res) {
					$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ');margin:0.2rem 0 0 0.2rem;" imgdata=' + res.target.result +'><span class="remove">删除</span></li>');
					$(".remove").unbind('tap').on('tap',function() {
						$(this).parents(".tu").remove();
					});
				}
				fr.readAsDataURL(file);
			}else{
				fun.tan('不能超过三张')
			}
		});
		
		//发表
		$(".bbs_fabiao").unbind('tap').on('tap',function(){
			var yyzz = '';
			$("#PostPost").parents('ul').find(".tu").each(function(i) {
				var listimg5 = $("#PostPost").parents('ul').find(".tu").eq(i).attr("imgdata");
				yyzz+= "@" + listimg5;
			});
			yyzz = yyzz.substr(1);
			var id=$(".bbs_list").attr('id');
			var content=$("#bbs_nr").val();
			if(content){
				Api.post(Api.tie_ping,{bbs_id:id,content:content,img:yyzz},function(obj){
					if(obj.s){
						$("#tz_pl .block2").remove();
						Api.post(Api.tie_info,{id:id},function(obj){
							if(obj.s){
								var d=obj.d;
								if(parm[1] == "bkl"){
									fun.bindOnce('.icon-zuojiantou','tap',function(){
										viewApi.go('#tpl_bkl',[d.data.cid]);
									});
								}
								$('.user_img').css("background-image",'url('+d.data.user_img+')');
								$('.user_name').text(d.data.user);
								$('.lxr_ctime').text(d.data.c_time);
								$('.lxr_zhan').text(d.data.zan);
								$('.lxr_pnum').text(d.data.p_num);
								$('.lxr_title').text('【' + d.data.c_name + '】' + d.data.title);
								$('.lxr_bk').text(d.data.c_name);
								$("#TZPre").empty();
								$('.bbs_content').html(d.data.conten);
								var PreImg = '';
								var num = d.data.img.length;
								$.each(d.data.img,function(i,d){
									if(num == 1){
										PreImg += '<img src="'+ d +'" width="100%">';
									}else if(num == 2 ){
										PreImg += '<img src="'+d+'" style="float:left;margin-right:1.5%;width:2.8rem;height:2.8rem;">';
									}else if(num >= 3){
										PreImg += '<img src="'+d+'" style="float:left;margin-right:1.5%; width:1.8rem;height:1.8rem;">';
									}
								});
								$("#TZPre").html(PreImg);
								$(".bbs_list").attr('id', d.data.id);
								$.each(d.p_data, function(ii, dd) {
									var tpl = '<div class="block2 clearfix"><div class="clearfix"><p class="">' + dd.nickname + '</p>';
				//					tpl += '<p class="score clearfix"></p>';
									tpl += '<p><span style="letter-spacing: 0.02rem;">' + dd.ctime + '</span></p>';
									tpl += '<p>' + dd.content + '</p>';
									tpl += '</div>';
									tpl += '<p class="fl-left img" style="">';
									if(dd.content_img.length > 1){
										$.each(dd.content_img, function(iii,ddd) {
											tpl += '<i style="background-image:url(' + ddd + ')"></i>';
										});
									}else{};
									tpl += '</p>';
									tpl += '</div>';
									$("#tz_pl").append(tpl);
								});
							}
						});
						$(".C_O_E,.rgba").hide();
						$(".TZ_Footer").show();
						$("#bbs_nr").val('');
					}
				});
			}else{
				fun.tan("内容不能为空");
			}
		});
		
		$(".TZ_Footer .text_content").unbind('tap').on('tap',function() {
			var token = fun.getCache('token');
			if(token){
				$(".C_O_E,.rgba").show();
				$(".TZ_Footer").hide();
				$('#bbs_nr').unbind('click').on('click',function(){
					setTimeout(function(){
						$(window).scrollTop(9999);
					},200);
				})
			}else{
				fun.tan('请先登录');
			}
		});
		$(".Q_X").unbind('tap').on('tap',function() {
			$(".C_O_E,.rgba").hide();
			$(".TZ_Footer").show();
		});
	},
	//添加好友
	ADD: function(){
		$("#Add_list").fadeOut();
		$("#Add_Friend").val("");
		$(".Add-list").empty();
		var user = fun.getCache("hxUser");
		$("#ADD_btn").unbind('tap').on('tap',function(){
			var name = $("#Add_Friend").val();
			if(name && name != null && name != undefined){
				hx.post(hx.around,{id:14,name:name},function(obj){
					if(obj.s){
						if(obj.d && obj.d != null && obj.d != undefined){
							var u = obj.d[0];
							$(".Add-list").empty();
							if(u.ournickname){
								k = '<li><i class="i1" style="background-image:url(' + u.ourimg + ')"></i><span>' + u.ournickname + '</span><span>' + u.username + '</span><button class="Add_Friend">添加</button></li>';
								$(".Add-list").append(k);
							} else {
								k = '<li><i class="i1" style="background-image:url(' + u.ourimg + ')"></i><span>' + u.nickname + '</span><span>' + u.username + '</span><button class="Add_Friend">添加</button></li>';
								$(".Add-list").append(k);
							}
							$(".Add_Friend").unbind('tap').on('tap',function(){
								if(name != user){
									pageFun.gt(1,name,1,user);//ok
									WebIMFun.doAddFriend(name, "请求加你为好友");
									fun.tan("请求已发送");
								}else{
									fun.tan("不能添加自己");
								}
							});
						} else {
							fun.tan("找不到用户");
						}
					} else {
						fun.tan("请检查搜索条件")
					}
				});
			} else {
				fun.tan("搜索条件不能为空");
			}
			
		});
	},
	//搜索群组
	ADD_Group: function() {
		$("#Add_list").fadeOut();
		$("#Add_Group_Input").val("");
		$(".Add-list").empty();
		$("#Add_Group_Btn").click(function() {
			var Group = $("#Add_Group_Input").val();
			if(Group && Group != null && Group != undefined){
				hx.post(hx.around,{id:7,name:Group},function(obj){
					if(obj.s){
						if(obj.d && obj.d != null && obj.d != undefined){
							var u = obj.d;
							$(".Add-list").empty();
							$.each(u, function(i, d) {
								if(d.name) {
									k = '<li><i class="i1" style="background-image:url(' + d.img + ')"></i><span>' + d.name + '</span><span class="group_id">' + d.group_id + '</span><button class="Add_Friend">添加</button></li>';
								} else {
									k = '<li><i class="i1" style="background-image:url(' + d.img + ')"></i><span>' + d.group_id + '</span><span class="group_id">' + d.group_id + '</span><button class="Add_Friend">添加</button></li>';
								}
								$(".Add-list").append(k);
							});
							$(".Add_Friend").unbind('tap').on('tap',function() {
								var group = $(this).parents("li").find(".group_id").text();
								var hxuser = fun.getCache("hxUser");
								hx.post(hx.around,{id:48,group_id:group,name:hxuser},function(obj){
									if(obj){
										fun.tan("申请成功");
									}
								});
								fun.tan("请求已发送");
							});
						} else {
							fun.tan("找不到群");
						}
					} else {
						fun.tan("请检查搜索条件");
					}
				});
			} else {
				fun.tan("搜索条件不能为空");
			}
		});
	},
	//创建群组
	CreateGroup: function() {
		$("#Add_list").fadeOut();
		$('.editpage').unbind('tap').on('tap',function() {
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);
		});
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$("#CreateGroup_header").show();
				$("#CreateGroup_header").css("background-image", 'url(' + res.target.result + ')');
				$("#CreateGroup_header").attr("imgdata", res.target.result);
			}
			fr.readAsDataURL(file);
		});
		var o = true;
		$("#CreateGroup_btn").unbind('tap').on('tap',function() {
			var name = $("#CreateGroup_name .content").text();
			var introduce = $(".xuzhi textarea").val();
			if(introduce == "" || introduce == null || introduce == undefined){
				var introduce = "什么都没有";	
			}
			var imgdata = $("#CreateGroup_header").attr("imgdata");
			var hxuser = fun.getCache("hxUser");
			if(name){
				if(imgdata){
					if(o == true){
						o = false;
						hx.post(hx.around,{id:44,groupname:name,desc:introduce,owner:hxuser,img:imgdata},function(obj){
							if(obj.s){
								fun.tan("创建成功");
								viewApi.back();
							};
						});
					}else{
						fun.tan("请勿重复注册")
					}
				}else{
					fun.tan("请上传头像");
				};
			}else{
				fun.tan("名称不能为空");
			};
		});
	},
	//我的订单
	My_Order: function() {
		list_order_lxr();
		$("#my_order").height($(window).height()-$(".pHead").height()-5);
		$("#my_order").css({"overflow-y":"scroll",'-webkit-overflow-scrolling':'touch'});
		function list_order_lxr() {
			Api.post(Api.list_order,{},function(obj) {
				if(obj.s) {
					if(obj.d == ''){
						$(".lxr_order_content").empty();
						$("#my_order").parent().append('<div id="MyOrderNoData" style="position:absolute;color:#ff5000;font-size:0.24rem;width:100%;height:0.5rem;line-height:0.5rem;top:50%;text-align:center;">还没有订单！</div>')
					}else{
						$("#MyOrderNoData").remove();
						var data = obj.d;
						var html = "";
						$(".lxr_order_content").empty();
						$.each(data, function(i, d) {
							html += '<li class="content clearfix M_li"><p class="O_D_H"><span>订单号：</span><span>' + d.code + '</span>';
							switch(d.status) {
								case '0':
									html += '<span class="fl-right">待付款</span></p>';
									break;
								case '1':
									html += '<span class="fl-right">待发货</span></p>';
									break;
								case '2':
									html += '<span class="fl-right">待收货</span></p>';
									break;
								case '3':
									html += '<span class="fl-right">待评价</span></p>';
									break;
								case '4':
									html += '<span class="fl-right">交易完成</span></p>';
									break;
								case '5':
									html += '<span class="fl-right">交易已关闭</span></p>';
									break;
							}
							$.each(d.data, function(ii, dd) {
								html += '<div class="lxr_ec M_div" style="overflow: hidden; margin:0.1rem 0;"><img src="' + dd.listimg + '" class="tu"/><p class="name">' + dd.title + dd.ds + '</p><p class="class">选择分类：' + dd.attr + '</p><p><span class="Price">￥' + dd.pirc + '</span><span class="fl-right number">X' + dd.num + '</span></p></div>';
							});
							html += '<p class="Price1 clearfix"><b>合计：￥' + d.cprice + '</b>';
	
							switch(d.status) {
								case '0':
									html += '<span class="L_J lxr_order_pay" code="' + d.code + '" >立即支付</span>';
									html += '<span  class="lxr_order_cancel" code="' + d.code + '">取消订单</span>';
									break;
								case '1':
									html += '<a href="tel:400-679-8808"><span class="L_J">联系客服</span></a>';
									break;
								case '2':
									html += '<span class="L_J lxr_order_confirm" code="' + d.code + '" >确认收货</span>';
									break;
								case '3':
									html += '<a href=""><span>马上评价</span></a>';
									break;
								case '4':
									html += '<span class="lxr_order_del" code="' + d.code + '" >删除订单</span>';
									break;
								case '5':
									html += '<span class="lxr_order_del" code="' + d.code + '">删除订单</span>';
									break;
							}
	
							html += '</p></li>';
						});
						$(".lxr_order_content").append(html);
						
						$(".Price1 a").unbind('tap').on('tap',function(){
							var p = "";
							$.each($(this).parents("li").find(".M_div"),function(i,d){
								p +=  '_'+$(this).attr("shop_id"); 
							})
							var l = $(this).parents("li").find(".O_D_H span:nth-child(2)").text();
							var k = l + p;
							$(this).parents("li").find("a").attr("href","#/tpl_Comment2/"+k);
							
						})
						$('.lxr_order_pay').unbind('tap').on('tap',function() {
							var code=$(this).attr('code');
							viewApi.go("#tpl_OrderDetails",code);
		//					location.href = "#/OrderDetails/"+code;
						})
						$(".order_evaluate").unbind('tap').on('tap',function(){
							var code = $(this).attr("code");
							viewApi.go("#tpl_Comment",code);
						});
						$('.lxr_order_cancel').unbind('tap').on('tap',function() {
							var code=$(this).attr('code');
							var _this = $(this);
							plus.nativeUI.confirm('确认取消？', function(e){
								if(e.index==0){
									Api.post(Api.cancel_order, {code:code}, function(obj) {
										if(obj.s){
											_this.parents("M_li").remove();
											list_order_lxr();
										}
									})
								}
							}, "系统提示", ["确认","取消"] );
						})
						
						$('.lxr_order_del').click(function() {
							var code=$(this).attr('code');
							var _this = $(this);
							plus.nativeUI.confirm('确认删除？', function(e){
								if(e.index==0){
									Api.post(Api.del_order, {code:code}, function(obj) {
										if(obj.s){
											_this.parents("M_li").remove();
											list_order_lxr();
										}
									});
								}
							}, "系统提示", ["确认","取消"] );
							
						});
						$('.lxr_order_confirm').click(function() {
							var code=$(this).attr('code');
							plus.nativeUI.confirm('确认收货？', function(e){
								if(e.index==0){
									Api.post(Api.confirm_good, {code:code}, function(obj) {
										if(obj.s){
											list_order_lxr();
										}
									})
								}
							}, "系统提示", ["确认","取消"] );
						})
					}
				}
			});
		}
	},

	//咨询客服  Miao 11-30
	Z_X_KF: function() {
		$("html,body,.mypage,.container,.Z_X_KF").css("height", "100%");
		$(".Z_X_KF , .pBody").css("background-color", "#fff");
		$(".Z_X_KF1 .btn").unbind('tap').on('tap',function() {
			var C = $(".Z_X_KF1 textarea").val();
			if(C){
				Api.post(Api.seme,{content:C},function(obj){
					if(obj.s){
						fun.tan("反馈成功");
						viewApi.back();
					} else {
						fun.tan("提交失败");
					}
				});
			} else {
				fun.tan("请输入内容");
			}
		});
	},

	//上传头像  Miao 11-30
	Upload_Avatar: function(_this){
		$("html,body,.mypage,.container,.Personal").css("height","auto");
		$("html,body,.mypage,.container,.modify1").css("height","auto");
		$(".save_cut").hide();
		
		$('#imgInput').unbind('change').on('change',function(){
			pageFun.showLoading();
			var file = document.getElementById('imgInput').files[0];
			if(window.FileReader){
				var fr = new FileReader();
				fr.onloadend = function(e){
					$('#imgView').attr('src', e.target.result).attr('d_data', e.target.result);
					$('#imgView').cropper({
						movable: false,
						resizable: false,
						aspectRatio: 1 / 1,
						highlight: false, //Boolean，默认值true。是否在剪裁框上显示白色的模态窗口。
						guides: false, //Boolean，默认值true。是否在剪裁框上显示虚线。
						resizable: false,
					});
					pageFun.closeLoading();
				};
				fr.readAsDataURL(file);
			}
		});
		
		$('#button2').unbind('click').click(function(){
			var dat = {
				src: $('#imgView').attr('src'),
			};
			Api.post(Api.up_haerimg,dat,function(data){
				$('.TX').empty();
				$('.TX').html('<img src="images/add2.png" id="imgView" class=""/><input id="imgInput" type="file" class=""/>');
				$("#tpl_Upload_Avatar").removeClass('popPageShow');
				pageFun.user();
				$("#imgView").attr("src","images/add2.png");
				$("#imgView").attr("d_data","");
			});
		});
		//重置
		$("#cut_rest").unbind('click').click(function(){
			$("#tpl_Upload_Avatar").removeClass('popPageShow');
			$('#imgView').attr('src',"images/add2.png");
			$('.TX').empty();
			$('.TX').html('<img src="images/add2.png" id="imgView" class=""/><input id="imgInput" type="file" class=""/>');	
		});
		
		//上传图片
		$("#button1").unbind('click').click(function(){
			pageFun.showLoading();
			var $image = $("#imgView");
			var boxData = $image.cropper("getData");
			var dat = {
				'imgdata': $('#imgView').attr('d_data'),
				'x': boxData.x,
				'y': boxData.y,
				'w': boxData.width,
				'h': boxData.height,
			};
			Api.post(Api.up_img,dat,function(data){
				pageFun.closeLoading();
				$(".cropper-container").remove();
				$('.cropper-hidden').removeClass('cropper-hidden'); 
				$('#imgView').attr('src',data.d).css({'width':'5.73rem','height':'5.73rem'}); 
				$(".save_cut").show();
			});
		});
	},
	//注册  Miao 11-28
	Z_C:function(){
//		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
//		$(".icon-zuojiantou").unbind("click").click(function(){
//			$("#tpl_Z_C").removeClass('popPageShow');
//			$("#tpl_Land").addClass('popPageShow');
//		});
//		$("#Z_C_phone").blur(function(){
//			var phone = $("#Z_C_phone").val();
//			if(!(Z_phone.test(phone))){
//				fun.tan("请输入正确手机号");
//			}
//		});
//		$("#Z_C_Password2").blur(function(){
//			var Password = $("#Z_C_Password").val();
//			var Password2 = $("#Z_C_Password2").val();
//			if(Password != Password2){
//				fun.tan("两次输入不一致");
//			}
//		});
//		$("#Z_C").unbind('tap').on('tap',function(){
//			var phone = $("#Z_C_phone").val();
//			var Password = $("#Z_C_Password").val();
//		});
	},
	//获取验证码  Miao 11-28
	getCode:function(){
		var phone = $("#Z_C_phone").val();
		Api.post(Api.getCode,{phone:phone},function(obj){
			if(obj.s){
				fun.tan("发送成功");
			}else{
				fun.tan("发送失败，请重试");
			}
		});
	},
	//注册 Miao 11/28
	reg: function() {
		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
		var l = true;
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			$('#tpl_Z_C').removeClass('popPageShow');
			$("#tpl_Land").addClass("popPageShow");
		});
		$("#Z_C_Code2").css("background-color", "#ff5000");
		$("#Z_C_Code2").unbind('tap').on('tap',function(){
			var phone = $('#Z_C_phone').val();
			if(!Z_phone.test(phone)){
				fun.tan('请输入正确的手机号');
			}else{
				if(l == true){
					l == false;
					Api.post(Api.verifyphone,{phone:phone},function(obj){
						if(obj.s){
							Api.post(Api.getCode,{phone:phone},function(obj){
								l = false;
								if(obj.s){
									fun.tan("验证码发送成功，请耐心等待");
									var i = 60;
									var a = setInterval(function() {
										i--;
										$("#Z_C_Code2").val("(" + i + ")重新发送");
										$("#Z_C_Code2").css("background-color", "#bbb");
									}, 1000);
									setTimeout(function() {
										clearInterval(a);
										$("#Z_C_Code2").val("获取验证码");
										$("#Z_C_Code2").css("background-color", "#ff5000");
										l = true;
									}, 60000);
								}else{
									l = true;
									fun.tan("验证码获取失败，请重试");
								}
							})
						}else{
							l = true;
							fun.tan("手机号已注册");
						}
					})
				}else{
					fun.tan('请勿重复点击')
				}
			}
		})
		$("#Z_C_Password2").blur(function() {
			var pwd1 = $("#Z_C_Password").val();
			var pwd2 = $("#Z_C_Password2").val();
			if(pwd1 != pwd2) {
				fun.tan("两次输入密码不一致");
			}
		});
		$("#Z_C").unbind('tap').on('tap',function(){
			var phone = $("#Z_C_phone").val();
			var pwd1 = $("#Z_C_Password").val();
			var pwd2 = $("#Z_C_Password2").val();
			var Code = $("#Z_C_Code").val();
			if(pwd1 != pwd2 && !(Z_phone.test(phone)) && !Code) {
				fun.tan("不能为空");
			} else {
				Api.post(Api.reg,{phone:phone,pwd:pwd2,code:Code},function(obj){
					if(obj.s == true){
						fun.tan("注册成功");
						fun.setCache('token', obj.d);
						fun.setCache('hxUser', phone);
						fun.setCache('hxPass', '123456');
						$("#tpl_Z_C").removeClass("popPageShow");
						$("#tpl_Land").removeClass('popPageShow');
						pageFun.hxreg();
						pageFun.user();
					} else {
						fun.tan("注册失败");
					}
				});
			}
		});
	},
	//注册环信
	hxreg: function() {
		var hxUser = fun.getCache('hxUser');
		var hxPass = fun.getCache('hxPass');
		WebIMFun.doReg(hxUser, hxPass, hxUser, function() {});
	},
	//登录 Miao 11/28
	login: function() {
		pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
		$("#login_phone").val('');
		$("#login_pwd").val('');
		$('#LandBack').unbind('tap').on('tap',function(){
			if($('.popPageShow').length>0){
				$('#MyUserLogin').show();
				$('.popPageShow').removeClass('popPageShow');
				if(view.currentPageId == 'tpl_My'){
					pageFun.ios_window('#c06633','UIStatusBarStyleDefault');
				}
			}else if(viewApi.canBack()){ //如果view可以后退，则执行view的后退;
				viewApi.back();
			}else{ //执行webview后退
				oldBack();
			}
		});
		// 注册
		fun.bindOnce(".Land-text .fl-right",'tap',function(){
			$("#tpl_Land").removeClass('popPageShow');
			$("#tpl_Z_C").addClass("popPageShow");
			$("#tpl_Password1").removeClass('popPageShow');
//			pageFun.Z_C();
			pageFun.reg();
			$('#MyUserLogin').hide();
		});
		// 忘记密码
		fun.bindOnce('.Land-text .fl-left','tap',function(){
			$("#tpl_Z_C").removeClass("popPageShow");
			$("#tpl_Land").removeClass('popPageShow');
			$("#tpl_Password1").addClass('popPageShow');
			pageFun.forget();
			$('#MyUserLogin').hide();
		});
		$('.oauth').unbind('tap').on('tap',function(){
			oauthtype=$(this).attr('oauth');
			pageFun.oauthlogin();
		});
		//登录 
		fun.bindOnce('#login','tap',function(){
			var loginPhone = $("#login_phone").val();
			var loginPwd = $("#login_pwd").val();
			var cid = fun.getCache("cid");
			pageFun.android_ios();
			Api.post(Api.login,{phone:loginPhone,pwd:loginPwd,cid:cid,eqsb:androidIos},function(obj){
				if(obj.s){
					fun.setCache('token', obj.d);
					$("#tpl_Password1,#tpl_Land,#tpl_Z_C").removeClass('popPageShow');
					$(".footer0").show();
					fun.setCache('hxUser',loginPhone);
					fun.setCache('hxPass','123456');
					fun.setCache('mesList', []);
					pageFun.hxLogin();
					$("#login_phone").val("");
					$("#login_pwd").val("");
					pageFun.indexshow();
					pageFun.user();
					pageFun.My();
				} else {
					fun.tan("登录失败，请检查手机号与密码");
				}
			});
		});
	},
	//第三方登入
	oauthlogin:function(){
		mui.plusReady(function() {
			plus.oauth.getServices(function(s){
				for(var i = 0; i < s.length; i++) {
					if(s[i].id==oauthtype){
						oauth=s[i];
						logintype();
					}
				}
			},function(e){
				fun.tan(JSON.stringify("获取登录认证失败："+e.message));
			});
			function logintype(){
				oauth.login(function(){
					oauth.getUserInfo( function(e){
						pageFun.logingpq(oauth);
					},function(e){});
				},function(e){
					fun.tan("["+e.code+"]："+e.message);
				});
			}
		});
	},
	logingpq:function(obj){
		var data = obj; 
		var cid = fun.getCache("cid");
		pageFun.android_ios();
		var parm = { openid:obj.authResult.openid, id:obj.id ,cid:cid,eqsb:androidIos}
		Api.post(Api.v_login,parm,function(obj){
			if(obj.s){
				var data=obj.d;
				if(data=="new"){
				var token=fun.getCache('token');
					if(token==false){
						pageFun.bangdin(oauth);
					}else{
						pageFun.bangdintow(oauth);
					}
				}else{
					fun.setCache('token', data.token);
					$("#tpl_Land").removeClass('popPageShow');
					$(".footer0").show();
					fun.setCache('hxUser',data.phone);
					fun.setCache('hxPass','123456');
					fun.setCache('mesList', []);
					pageFun.hxLogin();
					pageFun.user();
					$("#login_phone").val("");
					$("#login_pwd").val("");
				}
			}else{
			}
		});
	},
	//绑定qq或微信
	bangdin:function(obj){
		var oauthdata =obj;
		$("#tpl_bangdin").addClass('popPageShow');
		$("#tpl_Land").removeClass('popPageShow');
		$(".icon-zuojiantou").unbind('tap').on('tap',function(){
			$("#tpl_bangdin").removeClass('popPageShow');
			$("#tpl_Land").addClass('popPageShow');
		});
		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
		var l = true;
		$("#bangdin_phone").blur(function() {
			var phone = $("#bangdin_phone").val();
			if(!(Z_phone.test(phone))) {
				fun.tan("请输入正确的手机号");
				$("#bangdin_Code2").css("background-color","#bbbbbb");
			}else{
				$("#bangdin_Code2").css("background-color","#ff5000");
				$("#bangdin_Code2").unbind('tap').on('tap',function(){
					if(l == true){
						Api.post(Api.getCode,{phone:phone},function(obj){
							l = false;
							if(obj.s){
								fun.tan("验证码发送成功，请耐心等待");
								var i = 60;
								var a = setInterval(function() {
									i--;
									$("#bangdin_Code2").val("(" + i + ")重新发送");
									$("#bangdin_Code2").css("background-color", "#bbbbbb");
								}, 1000);
								setTimeout(function() {
									clearInterval(a);
									$("#bangdin_Code2").val("获取验证码");
									$("#bangdin_Code2").css("background-color", "#ff5000");
									l = true;
								}, 60000);
							} else {
								l = true;
								$("#bangdin_Code2").css("background-color", "#bbbbbb");
								fun.tan("验证码获取失败，请重试");
							}
						});
					}else{
						fun.tan('请勿重复提交');
					}
				});	
			}
		});
		$("#bangdin_Password").blur(function() {
			var pwd1 = $("#bangdin_Password").val();
			var pwd2 = $("#bangdin_Password2").val();
			if(pwd1 != pwd2) {
				fun.tan("两次输入密码不一致");
				return false;
			}
		});
		$("#bangdin").unbind('tap').on('tap',function() {
			var phone = $("#bangdin_phone").val();
			var pwd1 = $("#bangdin_Password").val();
			var pwd2 = $("#bangdin_Password2").val();
			var Code = $("#bangdin_Code").val();
			if(pwd1 != pwd2 && !(Z_phone.test(phone)) && !Code) {
				fun.tan("不能为空");
			} else {
				var data={phone:phone,pwd:pwd2,code:Code,data:oauthdata}
				Api.post(Api.bangdin,data,function(obj){
					if(obj.s){
						fun.setCache('token', obj.d);
						pageFun.indexshow();
						$("#tpl_Land").removeClass('popPageShow');
						$("#tpl_bangdin").removeClass('popPageShow');
						$('.popPageShow').removeClass('popPageShow');
						$(".footer0").show();
						fun.setCache('hxUser',phone);
						fun.setCache('hxPass','123456');
						fun.setCache('mesList', []);
						pageFun.hxLogin();
						pageFun.user();
						$("#bangdin_phone").val("");
						$("#bangdin_Code").val("");
						$("#bangdin_Password2").val("");
						$("#bangdin_Password").val("");
					} else {
						fun.tan(obj.m);
					}
				});
			}
		});
	},
	bangdintow:function(obj){
		if(obj.id=="weixin"){
			var unionid=obj.userInfo.unionid;
		}else{
			var unionid="";
		}
		var nickname=obj.userInfo.nickname;
		var openid=obj.authResult.openid;
		var id=obj.id;
		var data={
			nickname:nickname,
			openid:openid,
			id:id,
			unionid:unionid
		}
		Api.post(Api.bangdintow,{data:data},function(obj) {
			if(obj.s){
				pageFun.user();
			}else{
				fan.tan(obj.m);
			}
			
		});
	},
	//环信登录
	hxLogin: function() {
		var hxUser = fun.getCache('hxUser');
		var hxPass = fun.getCache('hxPass');
		WebIMFun.doLogin(hxUser, hxPass);
	},
	//获取用户信息 Miao 11/29
	user: function(){
		function ages(str){
		    var  r  =  str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
		    if(r==null) return false;
		    var d = new Date(r[1],r[3]-1,r[4]);
		    if(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]){
			    var  Y  =  new  Date().getFullYear();
			    return((Y-r[1]));
		    }
		    return("输入的日期格式错误！");
	   	}
		Api.post(Api.userinfo,{},function(obj) {
			if(obj.s){
				$("#MyUserLogin").hide();
				Y = obj.d;
				if(Y.wxnickname!=null&&Y.wxnickname!="" ) {
					$("#uswxinfo").html(Y.wxnickname+'<span class="iconfont icon-iconfontjiantou1"></span>');
					$("#uswxinfo").parent('.oauth').removeClass('oauth').removeAttr('oauth');
				}
				if(Y.qqnickname!=null&&Y.qqnickname!="") {
					$("#usqqinfo").html(Y.qqnickname+'<span class="iconfont icon-iconfontjiantou1"></span>');
					$("#usqqinfo").parent('.oauth').removeClass('oauth').removeAttr('oauth');
				}
				if(Y.nickname != null) {
					$("#my-name").text(Y.nickname);
					$("#P-name").text(Y.nickname);
					$("#MyUserLogin").hide();
				}else if(Y.wxnickname!=null) {
					$("#my-name").text(Y.wxnickname);
					$("#P-name").text(Y.wxnickname);
				
				}else if(Y.qqnickname!=null) {
					$("#my-name").text(Y.qqnickname);
					$("#P-name").text(Y.qqnickname);
				}else {
					$("#my-name").text("用户"+Y.phone);
					$("#P-name").text("用户"+Y.phone);
				}
				if(Y.img != null && Y.img != "") {
					$("#my-img").attr("src", Y.img);
					$("#P-img").attr("src", Y.img);
				} else {
					$("#my-img").attr("src", "images/t.jpg");
					$("#P-img").attr("src", "images/t.jpg");
				}
				if(Y.sig != null && Y.sig != "") {
					$("#my-qm").text(Y.sig);
					$("#P-sig").text(Y.sig);
				} else {
					$("#my-qm").html('你还没有个性签名');
					$("#P-sig").html('你还没有个性签名');
					$(".GX textarea").val('你还没有个性签名');
				}
				if(Y.age != null && Y.age != "") {
					var asd = ages(Y.age)
					$("#P-age").text(asd);
				}
				if(Y.sex == 0) {
					$("#P-sex").text("保密");
				} else if(Y.sex == 1) {
					$("#P-sex").text("男");
				} else if(Y.sex == 2) {
					$("#P-sex").text("女");
				}
				switch(Y.status) {
					case "f":
						$("#My-Maintain").hide();
						$("#My-Settled").show();
						break;
					case 0:
						$("#My-Maintain").hide();
						$("#My-Settled").show();
						$("#My-Settled li span").eq(1).text("申请入驻（审核中）");
						$("#My-Maintain").attr("href", "#/Settled");
						break;
					case 2:
						$("#My-Maintain").show();
						$("#My-Settled").hide();
						$("#My-Maintain").attr("href", "#/Maintain/" + Y.shop_id);
						break;
					default:
						$("#My-Maintain").show();
						$("#My-Settled").hide();
						$("#My-Maintain").attr("href", "#/tpl_My_Chess1/" + Y.shop_id);
				}
				if(Y.after==0){
					$("#lxr_after").css("background-color",'red');
				}
				if(Y.before==0){
					$("#lxr_before").css("background-color",'red');
				}
				if(Y.now==0){
					$("#lxr_now").css("background-color",'red');
				}
				if(Y.ping == 0){
					$("#evaluate").css("background-color",'red');
				}
			}else{
				if(obj.m == 'Token does not exist,Please login'){
					$("#MyUserLogin").show();
				}
			}
		});
	},
	//我的 Miao 11/28
	My: function() {
		$("#tpl_My").on('touchmove',function(e){
//	 		e.preventDefault();
	 	});
	 	
		pageFun.ios_window('#c06633','UIStatusBarStyleDefault');
		$('div.my').css('overflow','hidden');
		
		var He = $(window).height() - $('.NewMyPage header').height() - $('.NewMyPage nav').height() -$('#tabBar .footer').height() - 10;
		
		$('.My-main').height(He);
		
	 	var token = fun.getCache('token');
		if(!token){
			$("#my-name").text("");
			$("#my-qm").text("");
			$("#my-qm").find('.iconfont').removeClass('icon-shiliangzhinengduixiang9');
			$('#my-img').attr('src','images/t.jpg');
			$('#My-maintop li a i').css('background-color','');
//			$("#my-qm").find('span').text('未登录').css("color",'#777');
			$("#tpl_My .pBody").prepend("<div id='MyUserLogin' style='display:block;position:absolute;top:2.75rem;width:100%;z-index:1000;text-align:center;'><span style='color:#444;font-size:0.25rem;'>未登录 </span>&nbsp;<span style='color:#ff6700;font-size:0.25rem;'>立即登录</span></div>")
			$("#MyUserLogin").show();
			fun.bindOnce("#MyUserLogin span",'tap',function(){
//				$("#MyUserLogin").hide();
				$("#tpl_Land").addClass('popPageShow');
				pageFun.login();
			})
			fun.bindOnce('.My-main *,#tpl_My .pHead a,.My-maintop li','tap',function(event){
				var token = fun.getCache('token');
				if(!token){
					event.stopPropagation();
					$("#tpl_Land").addClass('popPageShow');
					pageFun.login();
					pageFun.ios_window("#ff5000","UIStatusBarStyleBlackOpaque");
				}
			})
		}else{
			pageFun.user();
			$("#MyUserLogin").hide();
		}
		pageFun.user();

		$(".footer li:nth-child(5) a p").css("color", "#ff5000");
		$(".footer0").show();
		$("html,body").css("height", "auto");
		var mesList = fun.getCache('mesList');
		if(mesList.length > 0) {
			$('.iconfont.icon-xx').html('<span class="dian"></span>');
		} else {
			$('.iconfont.icon-xx').empty();
		}
		$(".footer9").hide();
	},
	//个人信息 Miao 11/28
	Personal: function() {
		pageFun.user();
		$("head").append("<link>");
		css = $("head").children(":last");
		css.attr({
		    rel: "stylesheet",
		    type: "text/css",
		    href: "css/mui/mui.picker.min.css"
		});
		var token = fun.getCache('token');
		$('.editpage').click(function(){
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);
			$(".btn2").unbind("click").click(function(){
				var name = $(".mui-popup-input input").val();
				var namel = name.length;
				if(namel <= 10){
					if(name){
						Api.post(Api.up_nickname,{nickname:name,token:token},function(obj){
							if(obj.s){
								var content2 = $(".mui-popup-input input").val(); 
								$('#'+$('#popid').val()+' span:last-child').text(content2); 
								$(".btn1").click();
								fun.tan("修改成功");
							} else {
								fun.tan("网络忙，请重试");
							}
						});
					}else{
						fun.tan("昵称不能为空");
					}
				}else{
					fun.tan("昵称最多包含10个字符")
				}
			});
		});
		$(".li1").unbind('tap').on('tap',function() {
			$("#tpl_Upload_Avatar").addClass('popPageShow');
			pageFun.Upload_Avatar();
		});
		$("#P-GX").unbind('tap').on('tap',function() {
			var gx = $(".GX textarea").val();
			var gxl = gx.length;
			if(gxl <= 18) {
				Api.post(Api.up_sig,{sig:gx},function(obj) {
					if(obj.s){
						fun.tan("修改成功");
						$(".GX,.rgba").hide();
						pageFun.user();
					}else{
						fun.tan("修改失败");
					}
				});
			} else {
				fun.tan("签名最多包含18个字符")
			}
		});
		var i = 0;
		fun.bindOnce(".li2",'tap',function(){
			//mui 时间插件
			(function($){
				$.init();
				var result = $('#result')[0];
				var btns = $('.btn');
//				btns.each(function(i, btn) {
//					btn.addEventListener('tap', function() {
					fun.bindOnce('.li2','tap',function(){
						var optionsJson = '{"type":"date","beginYear":1930,"endYear":2017}';
						var options = JSON.parse(optionsJson);
						var id = demo2;
						var picker = new $.DtPicker(options);
						picker.show(function(rs) {
							var data = rs.value;
							picker.dispose();
						 	Api.post(Api.up_age,{age:data,token:token},function(obj){
					        	if(obj.s){
					        		fun.tan("修改成功");
					        		pageFun.user();
					        	}else{
					        		fun.tan("修改失败");
					        	}
					        });
						});
					})
//					}, false);
//				});
			})(mui);
		});
		// 性别选择
    	$("#sex-d").unbind('tap').on('tap',function(){
        	var sex = $(".input2").val();
        	if(sex == Y.sex){
        		$(".Gender,.rgba").hide();
        		fun.tan("修改成功");
        	}
    	 	Api.post(Api.up_sex,{sex:sex,token:token},function(obj){
    	 		if(obj.s){
    	 			fun.tan("修改成功")
    	 			$(".Gender,.rgba").hide();
    	 			pageFun.user();
    	 		}
    	 	});
    	});
	},
	//忘记密码  Miao 11/28
	forget: function() {
		$(".Password1").css("background-color", "#fff");
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			$("#tpl_Password1").removeClass('popPageShow');
			$("#tpl_Land").addClass('popPageShow');
		});
		var l = true;
		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
		$("#Pwd_phone").blur(function() {
			var phone = $("#Pwd_phone").val();
			if(!Z_phone.test(phone)){
				fun.tan('请输入正确的手机号');
			}else{
				$(".Password .absolute").css("background-color", "#ff5000");
				$(".Password .absolute").unbind('tap').on('tap',function(){
					if(l == true){
						Api.post(Api.getCode,{phone:phone},function(obj){
							l = false;
							if(obj.s){
								fun.tan("验证码发送成功，请耐心等待");
								var i = 60;
								var a = setInterval(function() {
									i--;
									$(".absolute").val("(" + i + ")重新发送");
									$(".absolute").css("background-color", "#bbbbbb");
								}, 1000);
								setTimeout(function() {
									clearInterval(a);
									$(".absolute").val("获取验证码");
									$(".absolute").css("background-color", "#ff5000");
									l = true;
								}, 60000);
							} else {
								l = true;
								$(".absolute").css("background-color", "#bbbbbb");
								fun.tan("验证码获取失败，请重试");
							}
						});
					}
				});
			}
		});
		$("#Pwd_pwd2").blur(function() {
			var pwd1 = $("#Pwd_pwd1").val();
			var pwd2 = $("#Pwd_pwd2").val();
			if(pwd1 != pwd2) {
				fun.tan("两次输入密码不一致");
			}
		});
		$(".btn").unbind('tap').on('tap',function() {
			var phone = $("#Pwd_phone").val();
			var pwd1 = $("#Pwd_pwd1").val();
			var pwd2 = $("#Pwd_pwd2").val();
			var Code = $("#Pwd_Code").val();
			if(pwd1 != pwd2 && !(Z_phone.test(phone)) && !Code) {
				fun.tan("不能为空");
			}else{
				Api.post(Api.forget,{phone:phone,code:Code,pwd:pwd2},function(obj){
					if(obj.s == true){
						fun.tan("密码修改成功");
						$("#tpl_Land").addClass('popPageShow');
						$("#tpl_Password1").removeClass('popPageShow');
					} else {
						fun.tan("密码修改失败，请重试");
					}
				});
			}
		});
	},
	
	asdg:function(){
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
			    yScroll = self.pageYOffset;
			    xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
			    yScroll = document.documentElement.scrollTop;
			    xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
			    yScroll = document.body.scrollTop;
			    xScroll = document.body.scrollLeft;  
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
	},
	//设置 Miao 11/29
	Set_Up: function() {
		var token = fun.getCache('token');
		var android_ios = navigator.userAgent;
		var isAndroid = android_ios.indexOf('Android') > -1 || android_ios.indexOf('Adr') > -1; //android终端
		var isiOS = !!android_ios.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if(isAndroid == true){
			$("#update").show();
		}else if(isiOS == true){
			$("#update").hide();
		}
		pageFun.user();
		$("#Exit-login").unbind('tap').on('tap',function(){
			fun.remove("token");
			fun.remove("hxUser");
			fun.remove("hxPass");
			fun.remove("ace");
			fun.remove("lng");
			fun.remove("lat");
			fun.tan("退出成功");
			$("#tpl_Land").addClass('popPageShow');
//			location.href="#/home";
			viewApi.go('#home');
			pageFun.login();
		});
		$("#modify2").unbind('tap').on('tap',function(){
			$(".pBody").css('background-color','#fff');
			$("#tpl_modify2").addClass("popPageShow");
			fun.bindOnce('.icon-zuojiantou','tap',function(){
				$("#tpl_modify2").removeClass("popPageShow");
				fun.bindOnce('.icon-zuojiantou','tap',function(){
					viewApi.back();
				})
			})
		});
		$("#update").unbind('tap').on('tap',function() {
			pageFun.version('setUp');
//			$(".rgba").show();
//			$(".update").show();
		});
		$(".button1").unbind('tap').on('tap',function() {
			$(".update").hide();
			$(".rgba").hide();
		})
		$('.oauth').unbind('tap').on('tap',function(){
			oauthtype=$(this).attr('oauth');
			pageFun.oauthlogin();
		});
		
		$("html,body,.mypage,.container,.modify2").css("height", "100%");
		$(".modify2	").css("background-color", "#fff");
		$("#M_PWD").unbind('tap').on('tap',function() {
			var YL = $("#M_YPWD").val();
			var xpwd1 = $("#M_XPWD1").val();
			var xpwd2 = $("#M_XPWD2").val();
			if( xpwd1 === xpwd2){
				Api.post(Api.up_pwd,{out_pwd:YL,new_pwd:xpwd2,token:token},function(obj){
					if(obj.s){
						fun.tan("修改成功");
					} else {
						fun.tan("修改失败");
					}
				})
			} else {
				fun.tan("两次输入密码不一致")
			}
		});
	},
	LD: function() {
		mui.ready(function() {
			var cityPicker3 = new mui.PopPicker({
				layer: 3
			});
			cityPicker3.setData(cityData3);
			fun.bindOnce("#showCityPicker3",'tap', function(event) {
				cityPicker3.show(function(items) {
					$("#cityResult3").text(items[0].text);
					$("#cityResult4").text(items[1].text);
					$("#cityResult5").text(items[2].text);
				});
			}, false);
		})
	},
	LD2: function() {
		mui.ready(function() {
			var cityPicker3 = new mui.PopPicker({
				layer: 3
			});
			cityPicker3.setData(cityData3);
			fun.bindOnce("#showCityPicker4",'tap', function(event) {
				cityPicker3.show(function(items) {
					$("#cityResult6").text(items[0].text);
					$("#cityResult7").text(items[1].text);
					$("#cityResult8").text(items[2].text);
				});
			}, false);
		})

	},
	//添加地址 Miao 11-30
	addressadd: function() {
		pageFun.LD();
		var token = fun.getCache("token");
		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
		$("#cityResult3").text("");
		$("#cityResult4").text("");
		$("#cityResult5").text("");
		$("#Add-name").val("");
		$("#Add-phone").val("");
		$("#Add-textarea").val("");
		$(".circular").removeClass('right').addClass('left');
		$(".SetUp .SetUp-btn.relative").css('background-color','#bbb');
		
		var kg = true;
		$("#ADD-tj").unbind('tap').on('tap',function() {
			var cityResult3 = $("#cityResult3").text();
			var cityResult4 = $("#cityResult4").text();
			var cityResult5 = $("#cityResult5").text();
			var name = $("#Add-name").val();
			var phone = $("#Add-phone").val();
			var New_textarea = $("#Add-textarea").val();
			if($(".circular").hasClass("right")) {
				var mrs = 1; //是默认地址
			} else {
				var mrs = 0; //不是默认地址
			}
			if(name && phone && New_textarea && cityResult3 && cityResult4) {
				if(!(Z_phone.test(phone))) {
					fun.tan("请填写正确手机号")
				} else {
					var data = {
						c_name: name,
						c_phome: phone,
						city: cityResult3,
						pro: cityResult4,
						area: cityResult5,
						add: New_textarea,
						status: mrs
					}
					if(kg == true){
						kg = false;
						Api.post(Api.add_addr, data, function(obj) {
							if(obj.s) {
								fun.tan("保存成功");
								viewApi.back();
							} else {
								fun.tan("保存失败");
								kg = true;
							}
						});
					}else{
						mui.toast("正在提交中");
					}
				}
			} else {
				fun.tan("请填写完整信息");
			}
		});
		fun.bindOnce('.btn2','tap',function(event){ 
			var _this = event.target;
			if($(_this).hasClass("right")) {
				$(_this).removeClass("right");
				$(_this).addClass("left");
				$(_this).parent().css("background-color","#bbb");
			}else{
				$(_this).removeClass("left");
				$(_this).addClass("right");
				$(_this).parent().css("background-color","#FF5000");
			}
		});
	},
	//页面添加地址
	Refresh: function() {
		var token = fun.getCache("token");
		Api.post(Api.addr,{token:token},function(obj){
			if(obj.s){
				var o = obj.d;
				$("#Address_j").empty();
				$.each(o, function(i, d) {
					if(o[i].status == 1) {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address">' + o[i].city + o[i].pro + o[i].area + o[i].add + '</p><p class="checkbox"><input type="radio" class="input2" name="radio" value="" /><span class="span-top">设置为默认</span><span class="fl-right span-top"><span><span class="BJ">编辑</span></span><span class="bj-sc">删除</span></span></p></li>';
					} else {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address">' + o[i].city + o[i].pro + o[i].area + o[i].add + '</p><p class="checkbox"><input type="radio" name="radio" value="" /><span class="span-top">设置为默认</span><span class="fl-right span-top"><span><span class="BJ">编辑</span></span><span class="bj-sc">删除</span></span></p></li>';
					}
					$("#Address_j").append(k);
				});
			}
		});
	},
	//确定删除
	deleteAddress2:function(cdid){
		Api.post(Api.del_addr,{id:cdid},function(obj){
			if(obj.s){
				fun.tan("删除成功");
				$("#tan3").hide();
				pageFun.Address();
				$(".rgba").hide();
			} else {
				fun.tan("删除失败，请重试");
			}
		});
	},
	//地址管理 Miao 11-30
	Address: function() {
		$(".footer0").hide();
		$('.icon-zuojiantou').unbind('tap').on('tap',function(){
			viewApi.go('#tpl_My');
		});
		(function(M) {
			//处理view的后退与webview后退
			var oldBack = M.back;
			M.back = function() {
				viewApi.go('#tpl_My');
			}; 
		})(mui);
		Api.post(Api.addr,{}, function(obj) {
			if(obj.s) {
				var o = obj.d;
				$("#Address_j").empty();
				$.each(o, function(i, d) {
					if(o[i].status == 1) {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address">' + o[i].city + " " + o[i].pro + " " + o[i].area + " " + o[i].add + '</p><p class="checkbox"><input type="radio" class="input2" name="radio" value="" /><span class="span-top span-top1">设置为默认</span><span class="fl-right span-top"><span><span class="BJ">编辑</span></span><span class="bj-sc">删除</span></span></p></li>';
					} else {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address">' + o[i].city + " " + o[i].pro + " " + o[i].area + " " + o[i].add + '</p><p class="checkbox"><input type="radio" name="radio" value="" /><span class="span-top">设置为默认</span><span class="fl-right span-top"><span><span class="BJ">编辑</span></span><span class="bj-sc">删除</span></span></p></li>';
					}
					$("#Address_j").append(k);
				});
				//删除地址
				$(".bj-sc").unbind('tap').on('tap',function() {
					var did = $(this).parents("li").attr("class");
					var did2 = $(this).parents("li").find("input").attr("class");
					var did4 = $(this).parents("li").next().attr("class");
					var did3 = $(this).parents("li").prev().attr("class");
					$(".rgba").show();
					fun.tan2("确认删除？");
					$("#tan3-d").unbind('tap').on('tap',function(){
						if(did2 == "input2"){
							if(fun.isnull(did3)){
								Api.post(Api.def,{id:did3},function(obj){
									if(obj.s){
										pageFun.deleteAddress2(did);
										pageFun.Refresh();
									} else {
										pageFun.deleteAddress2(did);
										pageFun.Refresh();
									}
								});
							}else{
								Api.post(Api.def,{id:did4},function(obj){
									if(obj.s){
										pageFun.deleteAddress2(did);
										pageFun.Refresh();
									} else {
										pageFun.deleteAddress2(did);
										pageFun.Refresh();
									}
								});
							}
						} else {
							pageFun.deleteAddress2(did);
						}

					});
					//取消
					$("#tan3-x").unbind('tap').on('tap',function() {
						$(".rgba").hide();
						$("#tan3").hide();
					});
				});
				// 设置默认地址
				$("#Address_j input").unbind('tap').on('tap',function(){
					if($(this).hasClass('input2') && $(this).next().hasClass('span-top1')){
						$(".checkbox input").removeClass("input2");
						$(".checkbox .span-top").removeClass("span-top1");
					}else{
						$(this).addClass("input2");
						$(this).next().addClass("span-top1");
					}
					var mr = $(this).parents("li").attr("class");
					Api.post(Api.def,{id:mr},function(obj){
						if(obj.s){
							mui.toast("设置成功");
						} else {
							mui.toast("设置失败请重试");
							pageFun.Refresh();
							pageFun.Address();
						}
					})
				});
				$(".BJ").unbind('tap').on('tap',function() {
					var BJid = $(this).parents("li").attr("class");
					viewApi.go("#tpl_EditAddress");
					Api.post(Api.addrone,{id:BJid},function(obj){
						if(obj.s){
							pageFun.LD2();
							var A = obj.d;
							$("#Edit-name").val(A.c_name);
							$("#Edit-phone").val(A.c_phome);
							$("#Edit-XX").val(A.add);
							$("#cityResult6").text(A.city);
							$("#cityResult7").text(A.pro);
							$("#cityResult8").text(A.area);
							if(A.status == 1) {
								$("#Edit-mr").removeClass("left");
								$("#Edit-mr").addClass("right");
								$(".SetUp-btn").css("background-color", "#ff5000");
							} else {
								$("#Edit-mr").removeClass("right");
								$("#Edit-mr").addClass("left");
								$(".SetUp-btn").css("background-color", "#bbb");
							}
							$("#Edit-btn").unbind('tap').on('tap',function() {
								pageFun.LD();
								var name = $("#Edit-name").val();
								var phone = $("#Edit-phone").val();
								var New_textarea = $("#Edit-XX").val();
								var cityResult6 = $("#cityResult6").text();
								var cityResult7 = $("#cityResult7").text();
								var cityResult8 = $("#cityResult8").text();
								var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
								if($("#Edit-mr").hasClass("right")) {
									var mrs = 1; //是默认地址
								} else {
									var mrs = 0; //不是默认地址
								}
								if(name && phone && New_textarea && cityResult6 && cityResult7) {
									if(!(Z_phone.test(phone))) {
										fun.tan("请输入正确的手机号");
									}else{
										Api.post(Api.up_addr,{id:BJid,c_name:name,c_phome:phone,city:cityResult6,pro:cityResult7,area:cityResult8,add:New_textarea,status:mrs},function(obj){
											if(obj.s){
												fun.tan("保存成功");
												pageFun.Refresh();
												viewApi.go('#tpl_Address');
											} else {
												fun.tan("保存失败");
											}
										});
									}
								} else {
									fun.tan("请填写完整信息");
								}
							});
						} else {
							fun.tan("获取失败")
						}
					})
				});
			}else{
				$("#Address_j").empty();
			}
		});
	},
//	//地址编辑 Miao 11-30
	EditAddress: function() {
//		var EXx = $("#Edit-XX").val();
//		var EName = $("#Edit-name").val();
//		var EPhone = $("#Edit-phone").val();
//		var EAddress = $("#Edit-Address").val();
//		var Z_phone = /^1[3|5|8]{1}[0-9]{9}$/;
//		$("#Edit-btn").unbind('tap').on('tap',function() {
//			if($("#Edit-mr").hasClass("left")) {
//				var mrs = 1; //1不是默认地址
//			} else {
//				var mrs = 2; //2是默认地址
//			}
//			if(EXx && EName && EPhone && EAddress) {
//				if(!(Z_phone.test(EPhone))) {
//					fun.tan("请填写正确手机号");
//				}else{
//					Api.post(Api.asd,{name:EXx,phone:EPhone,quyu:EAddress,xx:EXx,mr:mrs},function(obj){
//						if(obj.s){
//							fun.tan("保存成功");
//							location.href = "#/Address";
//						} else {
//							fun.tan("保存失败，请重试");
//						}
//					})
//				}
//			} else {
//				fun.tan("请把信息填写完整");
//				fun.tan(mrs);
//			}
//		});
	},
	//地址列表
	Addresslist: function() {
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			$("#tpl_Addresslist").removeClass('popPageShow');
			$('.icon-zuojiantou').unbind('tap').on('tap',function(){
				viewApi.back();
			});
		});
		Api.post(Api.addr,{},function(obj) {
			if(obj.s){
				var o = obj.d;
				$(".Address_jjj").empty();
				$.each(o, function(i, d) {
					if(o[i].status == 1) {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address3"><span>[默认地址]</span>' + o[i].city + o[i].pro + o[i].area + o[i].add + '</p></li>';
					} else {
						var k = '<li class="' + o[i].id + '"><p class="clearfix"><span class="fl-left">' + o[i].c_name + '</span><span class="fl-right">' + o[i].c_phome + '</span></p><p class="Address3">' + o[i].city + o[i].pro + o[i].area + o[i].add + '</p></li>';
					}
					$(".Address_jjj").append(k);
				});
				$(".Address_jjj").css("padding",'0')
				$("#Address_j li").unbind('tap').on('tap',function() {
					addressid = $(this).attr("class");
					Api.post(Api.addrone,{id:addressid},function(obj){
						if(obj.s){
							$("#address_list .content2").text(obj.d.city + " " + obj.d.pro + " " + obj.d.area);
							$("#address_list .content").text(obj.d.add);
							$(".AddressList .content2").text(obj.d.city + " " + obj.d.pro + " " + obj.d.area);
							$(".AddressList .content").text(obj.d.add);
							$("#tpl_Addresslist").removeClass('popPageShow');
							$(".Settled").show();
							$('.icon-zuojiantou').unbind('tap').on('tap',function(){
								viewApi.back();								
							});
						} else {
							fun.tan("添加失败");
						}
					});
				});
			}
		});
		$("#Addresslist-btn").unbind('tap').on('tap',function() {
			$("#tpl_Addresslist").removeClass('popPageShow');
			viewApi.go("#tpl_addressadd");
		});
	},
	LDS: function(){
		mui.ready(function() {
			var cityPicker3 = new mui.PopPicker({
				layer: 3
			});
			cityPicker3.setData(cityData3);
			$("#address_list").unbind('tap').on('tap',function(event) {
				cityPicker3.show(function(items) {
					$(".sheng").text(items[0].text);
					$(".shi").text(items[1].text);
					$(".qu").text(items[2].text);
				});
			});
		})
	},
	//申请入驻
	Settled: function(){
		pageFun.getSettled();
		$(".mui-popup").hide();
		pageFun.LDS();
		$("#ApplyMainScroll").height($(window).height()-$('.header_1').height()-$('#Settled_btn').height()).addClass('scroll');
		$('.editpage').unbind('tap').on('tap',function(){
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);
		});
		$('.upfile2').change(function(){
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$("#Apply #Apply1").show();
				$("#Apply #Apply1").css("background-image", 'url(' + res.target.result + ')');
				$("#Apply #Apply1").attr("imgdata", res.target.result);
			}
			fr.readAsDataURL(file);
		});
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ')" imgdata=' + res.target.result + '><span class="remove">删除</span></li>');
				$(".remove").unbind('tap').on('tap',function() {
					$(this).parents(".tu").remove();
				});
			}
			fr.readAsDataURL(file);
		});
		$("#Apply #Distributor-phone").attr("did","");
		$("#Apply #Distributor-phone").unbind('tap').on('tap',function(){
			$(".mui-popup-buttons .btn2 ").unbind('tap').on('tap',function(){
				var phone = $("#Apply #Distributor-phone .content").text();
				Api.post(Api.dealeryz,{phone:phone},function(obj){
					if(obj.s){
						Distributor = obj.d;
						$("#Apply #Distributor-phone").attr("did",obj.d);
					}else if(obj.s === false){
						fun.tan("经销商不存在");
						$("#Apply #Distributor-phone .content").text("");
						$("#Apply #Distributor-phone").attr("did","");
					}
				})
			})
		});
		var kg = true;
		$("#Settled_btn").unbind('tap').on('tap',function(){
			var Distributor = $("#Apply #Distributor-phone").attr("did");//经销商电话
			var shopname = $("#Apply #shop-name .content").text(); //店铺名称
			var name = $("#Apply #user-name .content").text(); //姓名
			var phone = $("#Apply #user-phone .content").text(); //手机
			var card = $("#Apply #user-id .content").text(); //身份证
			var ds = $("#Apply .xuzhi textarea").val(); //须知
			var pro = $("#Apply .sheng").text();
			var city = $("#Apply .shi").text();
			var area = $("#Apply .qu").text();
			var addr = $("#Apply #address_show .content").text();
			var card2 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
			var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
			var listimg = "";
			var showimg = "";
			var yyzz = "";
			var boss_img = "";
			pageFun.getPlace("#Apply #address_list",pro + city + area + addr,pro);
			var lng = $("#Apply #address_list").attr("lng"); //地址
			var lat = $("#Apply #address_list").attr("lat");
			$("#S_T_D_T1").parents('ul').find(".tu").each(function(i) {
				var listimg2 = $("#S_T_D_T1").parents('ul').find(".tu").eq(i).attr("imgdata");
				listimg = listimg2;
			});
			$("#S_T_D_T2").parents('ul').find(".tu").each(function(i) {
				var listimg3 = $("#S_T_D_T2").parents('ul').find(".tu").eq(i).attr("imgdata");
				showimg += "@" + listimg3;
			});
			showimg = showimg.substr(1);
			$("#S_T_D_T3").parents('ul').find(".tu").each(function(i) {
				var listimg4 = $("#S_T_D_T3").parents('ul').find(".tu").eq(i).attr("imgdata");
				boss_img+= "@" + listimg4;
			});
			boss_img = boss_img.substr(1);
			$("#S_T_D_T4").parents('ul').find(".tu").each(function(i) {
				var listimg5 = $("#S_T_D_T4").parents('ul').find(".tu").eq(i).attr("imgdata");
				yyzz+= "@" + listimg5;
			});
			yyzz = yyzz.substr(1);
			if(listimg && shopname && name && phone && card && pro && city && area && addr && ds){
				if(Z_phone.test(phone)){
					if(card2.test(card)){
						if(lat){
							if(kg == true){
								kg = false;
								Api.post(Api.apply_in_join,{lng: lng,
									lat: lat,
									name: name,
									shopname: shopname,
									ds: ds,
									did:Distributor,
									pro: pro,
									city: city,
									area: area,
									addr: addr,
									card: card,
									phone: phone,
									listimg: listimg,
									showimg: showimg,
									yyzz: yyzz,
									boss_img: boss_img}, function(obj) {
									if(obj.s){
										fun.tan("提交成功");
										viewApi.back();
										kg = false;
									}else{
										kg = true;
										fun.tan("提交失败");
									}
								});
							}
						}else{
							fun.tan("定位中,请重新填写或重新提交");
						}
					}else{
						fun.tan("请填写正确的身份证号");
					}
				}else{
					fun.tan("请填写正确的手机号");
				}
			}else{
				fun.tan("请填写完整信息");
			}
		});
	},
	// 附近麻将机店申请入驻
	Settled2: function(){
//		pageFun.getSettled();
		$(".mui-popup").hide();
		pageFun.LDS();
		$("#ApplyMainScroll").height($(window).height()-$('.header_1').height()-$('#Settled_btn').height()).addClass('scroll');
		$('.editpage').unbind('tap').on('tap',function(){
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);
		});
		
		$('#shangshi-timebtn').unbind('tap').on('tap',function(){
			var optionsJson = this.getAttribute('data-options') || '{}';
			var options = JSON.parse(optionsJson);
			var picker = new mui.DtPicker(options);
			picker.show(function(rs) {
				$('#shangshi-time .content2').text(rs.text);
				picker.dispose();
			});
		});
		
		$('.upfile2').change(function(){
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$("#Apply2 #Apply1").show();
				$("#Apply2 #Apply1").css("background-image", 'url(' + res.target.result + ')');
				$("#Apply2 #Apply1").attr("imgdata", res.target.result);
			}
			fr.readAsDataURL(file);
		});
		$('.upfile3').change(function(){
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$("#Apply2 #Apply").show();
				$("#Apply2 #Apply").css("background-image", 'url(' + res.target.result + ')');
				$("#Apply2 #Apply").attr("imgdata", res.target.result);
			}
			fr.readAsDataURL(file);
		});
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ')" imgdata=' + res.target.result + '><span class="remove">删除</span></li>');
				$(".remove").unbind('tap').on('tap',function() {
					$(this).parents(".tu").remove();
				});
			}
			fr.readAsDataURL(file);
		});
		$("#Apply2 #Distributor-phone").attr("did","");
		$("#Apply2 #Distributor-phone").unbind('tap').on('tap',function(){
			$(".mui-popup-buttons .btn2 ").unbind('tap').on('tap',function(){
				var phone = $("#Apply2 #Distributor-phone .content").text();
				Api.post(Api.dealeryz,{phone:phone},function(obj){
					if(obj.s){
						Distributor = obj.d;
						$("#Apply2 #Distributor-phone").attr("did",obj.d);
					}else if(obj.s === false){
						fun.tan("经销商不存在");
						$("#Apply2 #Distributor-phone .content").text("");
						$("#Apply2 #Distributor-phone").attr("did","");
					}
				})
			})
		});
		var kg = true;
		$("#Settled_btn").unbind('tap').on('tap',function(){
			var dom = $('#Apply2');
			
			var pinpainame = dom.find('#pinpai-name .content').text();
			
			var shangshitime = dom.find('#shangshi-time .content2').text();
			
			var Color = dom.find('#color-class .content').text();
			
			var shopname = dom.find("#shop-name .content").text(); //店铺名称
			var name = dom.find("#user-name .content").text(); //姓名
			var phone = dom.find("#user-phone .content").text(); //手机
			var card = dom.find("#user-id .content").text(); //身份证
			var ds = dom.find(".xuzhi textarea").val(); //须知
			var pro = dom.find(".sheng").text();
			var city = dom.find(".shi").text();
			var area = dom.find(".qu").text();
			var addr = dom.find("#address_show .content").text();
			var card2 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
			var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
			var listimg = "";
			var showimg = "";
			var yyzz = "";
			var boss_img = "";
			var jxs_img = '';
			pageFun.getPlace("#Apply2 #address_list",pro + city + area + addr,pro);
			var lng = $("#Apply2 #address_list").attr("lng"); //地址
			var lat = $("#Apply2 #address_list").attr("lat");
			
			$("#S_T_D_T1").parents('ul').find(".tu").each(function(i) {
				var listimg2 = $("#S_T_D_T1").parents('ul').find(".tu").eq(i).attr("imgdata");
				listimg = listimg2;
			});
			$("#S_T_D_T10").parents('ul').find(".tu").each(function(i) {
				var listimg2 = $("#S_T_D_T10").parents('ul').find(".tu").eq(i).attr("imgdata");
				jxs_img = listimg2;
			});
			$("#S_T_D_T2").parents('ul').find(".tu").each(function(i) {
				var listimg3 = $("#S_T_D_T2").parents('ul').find(".tu").eq(i).attr("imgdata");
				showimg += "@" + listimg3;
			});
			showimg = showimg.substr(1);
			$("#S_T_D_T3").parents('ul').find(".tu").each(function(i) {
				var listimg4 = $("#S_T_D_T3").parents('ul').find(".tu").eq(i).attr("imgdata");
				boss_img+= "@" + listimg4;
			});
			boss_img = boss_img.substr(1);
			$("#S_T_D_T4").parents('ul').find(".tu").each(function(i) {
				var listimg5 = $("#S_T_D_T4").parents('ul').find(".tu").eq(i).attr("imgdata");
				yyzz+= "@" + listimg5;
			});
			yyzz = yyzz.substr(1);
			if(listimg && shopname && name && phone && card && pro && city && area && addr && ds && pinpainame && shangshitime && Color){
				if(Z_phone.test(phone)){
					if(card2.test(card)){
						if(lat){
							if(kg == true){
								kg = false;
								Api.post(Api.nearby_shop_apply,{lng: lng,
									lat: lat,
									name: name,
									shop_name: shopname,
									desc_img : jxs_img,
									instructions : ds,
									brand_name:pinpainame,
									listing_time:shangshitime,
									color:Color,
									province : pro,
									city: city,
									district : area,
									address : addr,
									id_card : card,
									mobile : phone,
									picture : listimg,
									pictures : showimg,
									business_license: yyzz,
									boss_img : boss_img}, function(obj) {
									if(obj.s){
										fun.tan("提交成功");
										viewApi.back();
										kg = false;
									}else{
										kg = true;
										fun.tan("提交失败");
									};
								});
							}
						}else{
							fun.tan("定位中,请重新填写或重新提交");
						}
					}else{
						fun.tan("请填写正确的身份证号");
					}
				}else{
					fun.tan("请填写正确的手机号");
				}
			}else{
				fun.tan("请填写完整信息");
			}
		});
	},
	//申请入驻 获取申请信息
	getSettled:function(){
		Api.post(Api.shop_updata_set,{},function(obj){
			if(obj.s){
				var u= obj.d;
				if(u.shopname){
					if($("#user-name").hasClass("editpage")){
						$(".pHead h2").text("修改资料");
						$(".Settled button").text("确认修改");
					}else{
						$(".pHead h2").text("店铺管理");
						M_Id = u.id;
					}
					$(".pHead").css("z-index","999");
					$("#shop-name .content").text(u.shopname); //店铺名称
					$("#user-name .content").text(u.name); //姓名
					$("#user-phone .content").text(u.phone); //手机
					$("#user-id .content").text(u.card); //
					$(".xuzhi textarea").val(u.ds);
					$(".sheng").text(u.pro);
					$(".shi").text(u.city);
					$(".qu").text(u.area);
					$("#Distributor-phone .content,#d-phone .content").text(u.dphone);
					$("#address_show .content").text(u.addr);
					Api.post(Api.getimgBaseData,{url:u.listimg},function(obj){
						$('#Apply1,#Apply2').css("background-image",'url(' + obj.d + ')');
						$('#Apply1,#Apply2').attr("imgdata",obj.d);
						$('#Apply1,#Apply2').css("display","block");
					});
					$.each(u.showimg,function(i,d){
						Api.post(Api.getimgBaseData,{url:d},function(obj){
							if(obj.s){
								$("#S_T_D_T2").parents("ul").find(".add").before('<li class="tu" style="background-image:url(' + obj.d + ')" imgdata=' + obj.d + '><span class="remove">删除</span></li>');								
							}
						});
					});
					$.each(u.boss_img,function(i,d){
						Api.post(Api.getimgBaseData,{url:d},function(obj){
							if(obj.s){
								$("#S_T_D_T3").parents("ul").find(".add").before('<li class="tu" style="background-image:url(' + obj.d + ')" imgdata=' + obj.d + '><span class="remove">删除</span></li>');
							}
						});
					});
					$.each(u.yyzz,function(i,d){
						Api.post(Api.getimgBaseData,{url:d},function(obj){
							if(obj.s){
								$("#S_T_D_T4").parents("ul").find(".add").before('<li class="tu" style="background-image:url(' + obj.d + ')" imgdata=' + obj.d + '><span class="remove">删除</span></li>');
							}
						});
					});
					$(function removedom (){
						$(".remove").unbind("click").click(function() {
							$(this).parents(".tu").remove();
						});
					});
					$("#Distributor-phone").attr("did","");
					$("#Distributor-phone").unbind('tap').on('tap',function(){
						$(".mui-popup-buttons .btn2 ").unbind('tap').on('tap',function(){
							var phone = $("#Distributor-phone .content").text();
							Api.post(Api.dealeryz,{phone:phone},function(obj){
								if(obj.s){
									Distributor = obj.d;
									$("#Distributor-phone").attr("did",obj.d);
								}else if(obj.s === false){
									fun.tan("经销商不存在");
									$("#Distributor-phone .content").text("");
									$("#Distributor-phone").attr("did","");
								}
							})
						})
					});
					$("#Settled_btn").unbind("click").click(function(){
						var Distributor = $("#Distributor-phone").attr("did");
						var id = u.id;
						var name = $("#user-name .content").text();
						var shopname = $("#shop-name .content").text();
						var phone = $("#user-phone .content").text();
						var card = $("#user-id .content").text();
						var ds = $(".xuzhi textarea").val();
						var pro = $(".sheng").text();
						var city = $(".shi").text();
						var area = $(".qu").text();
						var listimg = "";
						var showimg = "";
						var yyzz = "";
						var boss_img = "";
						var addr = $("#address_show .content").text();
						pageFun.getPlace("#address_list",pro + city + area + addr,pro);
						var lng = $("#address_list").attr("lng");
						var lat = $("#address_list").attr("lat");
						$("#S_T_D_T1").parents('ul').find(".tu").each(function(i) {
							var listimg2 = $("#S_T_D_T1").parents('ul').find(".tu").eq(i).attr("imgdata");
							listimg = listimg2;
						});
						$("#S_T_D_T2").parents('ul').find(".tu").each(function(i) {
							var listimg3 = $("#S_T_D_T2").parents('ul').find(".tu").eq(i).attr("imgdata");
							showimg += "@" + listimg3;
						});
						showimg = showimg.substr(1);
						$("#S_T_D_T3").parents('ul').find(".tu").each(function(i) {
							var listimg4 = $("#S_T_D_T3").parents('ul').find(".tu").eq(i).attr("imgdata");
							boss_img+= "@" + listimg4;
						});
						boss_img = boss_img.substr(1);
						$("#S_T_D_T4").parents('ul').find(".tu").each(function(i) {
							var listimg5 = $("#S_T_D_T4").parents('ul').find(".tu").eq(i).attr("imgdata");
							yyzz+= "@" + listimg5;
						});
						yyzz = yyzz.substr(1);
						Api.post(Api.updata_shop,{id:id,lng:lng,lat: lat,name:name,shopname: shopname,
								ds: ds,
								did:Distributor,
								pro: pro,
								city: city,
								area: area,
								addr: addr,
								card: card,
								phone: phone,
								listimg: listimg,
								showimg: showimg,
								yyzz: yyzz,
								boss_img: boss_img},function(){
							if(obj.s){
								fun.tan("修改成功");
								viewApi.back();
							}
						});
					})
				}
			}
		});
	},
	//申请加盟
	A_T_J: function() {
		$(".A_T_J").css("background-color","#fff");
		$('.editpage').unbind('tap').on('tap',function() {
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);	
		});
		$(".AddressList").unbind('tap').on('tap',function() {
			$("#tpl_Addresslist").addClass('popPageShow');
			pageFun.Addresslist();
		});
		$(".P a").unbind('tap').on('tap',function(){
			$("#tpl_clause").addClass('popPageShow');
			fun.bindOnce('.icon-zuojiantou','tap',function(){
				$("#tpl_clause").removeClass('popPageShow');
				fun.bindOnce('.icon-zuojiantou','tap',function(){
					viewApi.back();
				})
			})
		});
		$(".ZJ").unbind('tap').on('tap',function(){
			$(".ul_E").toggleClass("Add");
			if($(".ul_E").hasClass("Add")){
				$(".ul_E").fadeIn();
				$(".icon-xsj").addClass("XZ");
			}else{
				$(".ul_E").fadeOut();
				$(".icon-xsj").removeClass("XZ");
			}
		});
		$(".ul_E li").unbind('tap').on('tap',function(){
			var this_text = $(this).text();
			$(".ZJ span:nth-last-child(1)").text(this_text);
			$(".ul_E").fadeOut();
			$(".icon-xsj").removeClass("XZ");
		});
		$(".P .iconfont").unbind('tap').on('tap',function(){
			$(this).toggleClass("icon-duigou");
		});
		var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
		var l = true;
		$(".Join").unbind('tap').on('tap',function(){
			var myname = $("#A_T_J_name span:nth-last-child(1)").text();
			var myphone = $("#A_T_J_phone span:nth-last-child(1)").text();
			var myaddress = $(".AddressList").find(".content").text();
			var myaddress2 = $(".AddressList").find(".content2").text();
			var mymoney = $(".ZJ span:nth-last-child(1)").text();
			if($(".P .iconfont").hasClass("icon-duigou")){
				if(myname && myphone && myaddress && mymoney){
					if(Z_phone.test(myphone)){
						if(l == true){
							Api.post(Api.apply_add,{name:myname,phone:myphone,adress:myaddress+myaddress2,money:mymoney},function(obj){
								if(obj.s){
									fun.tan("申请成功");
									viewApi.go("#home");
									$("#A_T_J_name").parent().find('li span:nth-last-child(1),li .content2,li .content').text('');
								}else{
									l = false;
									if(obj.m == '已经申请过'){
										fun.tan('正在审核中，请勿重复申请');
									}
								}
							});
						}else{
							fun.tan('请勿重复提交');
						}
					}else{
						fun.tan("请填写正确手机号");
					}
				}else{
					fun.tan("请填写完整信息");
				}
			}else{
				fun.tan("请阅读并同意加盟条款");
			}
		})
	},
	//我的评价
	My_evaluate:function(){
		var parm = viewApi.parms;
		plp = parm[0];
		Api.post(Api.shop_info,{id:plp},function(obj){
			if(obj.s){
				var u = obj.d.pinglun_info;
				var k = "";
				$.each(u,function(i,d){
					k += '<div class="block2 clearfix"><div class="left"><p class="">'+d.nickname+'</p><p class="score clearfix"><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span><span class="iconfont icon-wujiaoxing"></span></p><p>'+d.content+'</p></div><p class="fl-left"><span style="letter-spacing: 0.02rem;">'+d.ctime+'</span></p> <p class="fl-left img" style="">';
					$.each(d.ping_img,function(ii,dd){
						k += '<i style="background-image:url('+dd+')"></i>';
					});
					k += '</p></div>';
				});
				$(".Addlist").append(k);
				$.each(u, function(i,d) {
	    			$(".block2").eq(i).find(".icon-wujiaoxing").slice(0,d.xing).css("color","#ff9d09");
				});
			}
		})
	},
	//预约订单
	Order1:function(){
		Api.post(Api.shop_yuyuelist,{},function(obj){
			if(obj.s){
				var u = obj.d;
				$(".Addlist").empty();
				$.each(u, function(i,d) {
					var k = '<li class="title"><i></i><span>下单时间：'+d.ctime+'</span></li><li class="Division"><p class="one"><span>昵称：'+d.name+'</span><span class="fl-right">预约人数：'+d.num+'</span></p><p>手机号：'+d.phone+'</p><p>预约时间：9月13日 14:00-16:30</p></li>';
					$(".Addlist").append(k);
				});
			}
		})
	},
	//我的店铺
	My_Chess1:function(){
		var parm = viewApi.parms;
		plp = parm[0];
		$(".evaluate").parent().attr("href", "#/tpl_My_evaluate/" + plp);
		Api.post(Api.shop_onandup,{},function(obj){
			if(obj.s){
				var u = obj.d;
				if(u == 1){
					$(".Reserve .SetUp-btn").css("background-color","#FF5000");
					$(".Reserve .SetUp-btn span").removeClass("left");
					$(".Reserve .SetUp-btn span").addClass("right");
				}else if(u == 3){
					$(".Reserve .SetUp-btn").css("background-color","#bbb");
					$(".Reserve .SetUp-btn span").removeClass("right");
					$(".Reserve .SetUp-btn span").addClass("left");
				}
			}
		});
		$(".Reserve .SetUp-btn span").unbind('tap').on('tap',function() {
			if($(this).hasClass("right")) {
				var u = 1;
				Api.post(Api.shop_openup,{type:u},function(obj){
					if(obj.s){
						fun.tan("设置成功，已开启");
					}
				});
			}else{
				var u = 3;
				Api.post(Api.shop_openup,{type:u},function(obj){
					if(obj.s){
						fun.tan("设置成功，已关闭");
					}
				})
			}
		});
	},
	//店铺管理  Miao 2016-12-08 
	Maintain: function() {
		pageFun.getSettled();
		$('.editpage').unbind('tap').on('tap',function() {
			var title = $(this).attr('title');
			var info = $(this).attr('info');
			$('#popid').val($(this).attr('id'));
			fun.muitan(title, info);
		});
		$('.upfile').change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$(_this).parents('li').before('<li class="tu" style="background-image:url(' + res.target.result + ')" imgdata=' + res.target.result + '><span class="remove">删除</span></li>');
				$(".remove").unbind('tap').on('tap',function(){
					$(this).parents(".tu").remove();
				});
			}
			fr.readAsDataURL(file);
		});
		$("#Settled_btn2").unbind("click").click(function(){
			var name = $("#shop-name .content").text();
			var phone = $("#user-phone .content").text();
			var ds = $(".xuzhi textarea").val();
			var listimg = "";
			var showimg = "";
			$("#S_T_D_T1").parents('ul').find(".tu").each(function(i) {
				var listimg2 = $("#S_T_D_T1").parents('ul').find(".tu").eq(i).attr("imgdata");
				listimg = listimg2;
			});
			$("#S_T_D_T2").parents('ul').find(".tu").each(function(i) {
				var listimg3 = $("#S_T_D_T2").parents('ul').find(".tu").eq(i).attr("imgdata");
				showimg += "@" + listimg3;
			});
			showimg = showimg.substr(1);
			Api.post(Api.decorate_shop,{shopname:name,phone:phone,ds:ds,listimg:listimg,showimg:showimg,id:M_Id},function(obj){
				if(obj.s){
					fun.tan("修改成功");
					viewApi.back();
				}
			});
		});
	},
	Status_lxr: function(type) {
		Api.post(Api.up_readstatus,{type:type}, function(obj) {
			if(obj.s){}
		});
	},
	//待付款
	FuKuan: function() {
		pageFun.Status_lxr(0);
		FuKuan();
		$("#stay_payment").height($(window).height()-$(".pHead").height()-5);
		$("#stay_payment").css({"overflow-y":"scroll",'-webkit-overflow-scrolling':'touch'});
		function FuKuan(){
			Api.post(Api.order_type, {type:0}, function(obj) {
				if(obj.s){
					if(obj.d == ''){
						$(".lxr_order_FuKuan").empty();
						$("#stay_payment").parent().append('<div id="FuKuanNoData" style="position:absolute;color:#ff5000;font-size:0.24rem;width:100%;height:0.5rem;line-height:0.5rem;top:50%;text-align:center;">还没有待付款订单！</div>')
					}else{
						$('#FuKuanNoData').remove();
						var data = obj.d;
						var html = "";
						$(".lxr_order_FuKuan").empty();
						$.each(data, function(i, d) {
							html += '<li class="content clearfix M_li"><p class="O_D_H"><span>订单号：</span><span>' + d.code + '</span>';
							switch(d.status) {
								case '0':
									html += '<span class="fl-right">待付款</span></p>';
									break;
								case '1':
									html += '<span class="fl-right">待发货</span></p>';
									break;
								case '2':
									html += '<span class="fl-right">待收货</span></p>';
									break;
								case '3':
									html += '<span class="fl-right">待评价</span></p>';
									break;
								case '4':
									html += '<span class="fl-right">交易完成</span></p>';
									break;
								case '5':
									html += '<span class="fl-right">交易已关闭</span></p>';
									break;
							}
							$.each(d.data, function(ii, dd) {
								html += '<div class="lxr_ec M_div" style="overflow: hidden"><img src="' + dd.listimg + '" class="tu"/><p class="name">' + dd.title + dd.ds + '</p><p class="class">选择分类：' + dd.attr + '</p><p><span class="Price">￥' + dd.pirc + '</span><span class="fl-right number">X' + dd.num + '</span></p></div>';
							});
							html += '<p class="Price1 clearfix"><b>合计：￥' + d.cprice + '</b>';
							switch(d.status) {
								case '0':
									html += '<span class="L_J lxr_order_pay" code="' + d.code + '" >立即支付</span>';
									html += '<span  class="lxr_order_cancel" code="' + d.code + '">取消订单</span>';
									break;
								case '1':
									html += '<span class="L_J">联系客服</span>';
									break;
								case '2':
									html += '<span class="L_J lxr_order_confirm" code="' + d.code + '" >确认收货</span>';
									break;
								case '3':
									html += '<span >马上评价</span>';
									break;
								case '4':
									html += '<span class="lxr_order_del" code="' + d.code + '" >删除订单</span>';
									break;
								case '5':
									html += '<span class="lxr_order_del" code="' + d.code + '">删除订单</span>';
									break;
							}
							html += '</p></li>';
						});
						$(".lxr_order_FuKuan").append(html);
						$('.lxr_order_pay').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							viewApi.go("#tpl_OrderDetails",code);
						})
	
						$('.lxr_order_cancel').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							var _this = $(this);
							plus.nativeUI.confirm('确认取消？', function(e){
								if(e.index==0){
									Api.post(Api.cancel_order, {code: code}, function(obj) {
										if(obj.s) {
											_this.parents("M_li").remove();
											FuKuan();
										}
									})
								}
							}, "系统提示", ["确认","取消"] );
						});
						$('.lxr_order_del').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.del_order, {
								code: code
							}, function(obj) {
								if(obj.s) {
									FuKuan();
								}
							})
						});
						$('.lxr_order_confirm').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.confirm_good, {
								code: code
							}, function(obj) {
								if(obj.s) {
									FuKuan();
								}
							})
						})
					}
				}
			});
		}
		fun.bindOnce('.icon-zuojiantou','tap',function(){
			viewApi.go("#tpl_My");
		});
	},
	//待发货
	FaHuo: function() {
		pageFun.Status_lxr(1);
		FaHuo();
		$("#stay_DeliverGoods").height($(window).height()-$(".pHead").height()-5);
		$("#stay_DeliverGoods").css({"overflow-y":"scroll",'-webkit-overflow-scrolling':'touch'});
		function FaHuo(){
			Api.post(Api.order_type, {type:1}, function(obj) {
				if(obj.s) {
					if(obj.d == ''){
						$(".lxr_order_FaHuo").empty();
						$("#stay_DeliverGoods").parent().append('<div id="FaHuoData" style="position:absolute;color:#ff5000;font-size:0.24rem;width:100%;height:0.5rem;line-height:0.5rem;top:50%;text-align:center;">还没有待发货订单！</div>')
					}else{
						$('#FaHuoData').remove();
						var data = obj.d;
						var html = "";
						$(".lxr_order_FaHuo").empty();
						$.each(data, function(i, d) {
							html += '<li class="content clearfix M_li"><p class="O_D_H"><span>订单号：</span><span>' + d.code + '</span>';
							switch(d.status) {
								case '0':
									html += '<span class="fl-right">待付款</span></p>';
									break;
								case '1':
									html += '<span class="fl-right">待发货</span></p>';
									break;
								case '2':
									html += '<span class="fl-right">待收货</span></p>';
									break;
								case '3':
									html += '<span class="fl-right">待评价</span></p>';
									break;
								case '4':
									html += '<span class="fl-right">交易完成</span></p>';
									break;
								case '5':
									html += '<span class="fl-right">交易已关闭</span></p>';
									break;
							}
							$.each(d.data, function(ii, dd) {
								html += '<div class="lxr_ec M_div" style="overflow: hidden "><img src="' + dd.listimg + '" class="tu"/><p class="name">' + dd.title + dd.ds + '</p><p class="class">选择分类：' + dd.attr + '</p><p><span class="Price">￥' + dd.pirc + '</span><span class="fl-right number">X' + dd.num + '</span></p></div>';
							});
							html += '<p class="Price1 clearfix"><b>合计：￥' + d.cprice + '</b>';
							switch(d.status) {
								case '0':
									html += '<span class="L_J lxr_order_pay" code="' + d.code + '" >立即支付</span>';
									html += '<span  class="lxr_order_cancel" code="' + d.code + '">取消订单</span>';
									break;
								case '1':
									html += '<a href="tel:400-679-8808"><span class="L_J">联系客服</span></a>';
									break;
								case '2':
									html += '<span class="L_J lxr_order_confirm" code="' + d.code + '" >确认收货</span>';
									break;
								case '3':
									html += '<span >马上评价</span>';
									break;
								case '4':
									html += '<span class="lxr_order_del" code="' + d.code + '" >删除订单</span>';
									break;
								case '5':
									html += '<span class="lxr_order_del" code="' + d.code + '">删除订单</span>';
									break;
							}
							html += '</p></li>';
						});
						$(".lxr_order_FaHuo").append(html);
	
						$('.lxr_order_pay').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							viewApi.go("#tpl_OrderDetails",code);
						})
	
						$('.lxr_order_cancel').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.cancel_order, {
								code: code
							}, function(obj) {
								if(obj.s) {
									FaHuo();
								}
							})
						})
						$('.lxr_order_del').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.del_order, {
								code: code
							}, function(obj) {
								if(obj.s) {
									FaHuo();
								}
							})
						});
						$('.lxr_order_confirm').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.confirm_good, {
								code: code
							}, function(obj) {
								if(obj.s) {
									FaHuo();
								}
							})
						})
					}
				}
			});
		}
	},
	//待收货
	ShouHuo: function() {
		pageFun.Status_lxr(2);
		ShouHuo();
		$("#stay_GoodsReceipt").height($(window).height()-$(".pHead").height()-5);
		$("#stay_GoodsReceipt").css({"overflow-y":"scroll",'-webkit-overflow-scrolling':'touch'});
		function ShouHuo(){
			Api.post(Api.order_type, {type:2}, function(obj) {
				if(obj.s) {
					if(obj.d == ''){
						$(".lxr_order_ShouHuo").empty();
						$("#stay_GoodsReceipt").parent().append('<div id="NoDataDiv" style="position:absolute;color:#ff5000;font-size:0.24rem;width:100%;height:0.5rem;line-height:0.5rem;top:50%;text-align:center;">还没有待收货订单！</div>')
					}else{
						$('#NoDataDiv').remove();
						var data = obj.d;
						var html = "";
						$(".lxr_order_ShouHuo").empty();
						$.each(data, function(i, d) {
							html += '<li class="content clearfix M_li"><p class="O_D_H"><span>订单号：</span><span>' + d.code + '</span>';
							switch(d.status) {
								case '0':
									html += '<span class="fl-right">待付款</span></p>';
									break;
								case '1':
									html += '<span class="fl-right">待发货</span></p>';
									break;
								case '2':
									html += '<span class="fl-right">待收货</span></p>';
									break;
								case '3':
									html += '<span class="fl-right">待评价</span></p>';
									break;
								case '4':
									html += '<span class="fl-right">交易完成</span></p>';
									break;
								case '5':
									html += '<span class="fl-right">交易已关闭</span></p>';
									break;
							}
							$.each(d.data, function(ii, dd) {
							html += '<div class="lxr_ec M_div" style="overflow: hidden"><img src="' + dd.listimg + '" class="tu"/><p class="name">' + dd.title + dd.ds + '</p><p class="class">选择分类：' + dd.attr + '</p><p><span class="Price">￥' + dd.pirc + '</span><span class="fl-right number">X' + dd.num + '</span></p></div>';
							});
							html += '<p class="Price1 clearfix"><b>合计：￥' + d.cprice + '</b>';
	
							switch(d.status) {
								case '0':
									html += '<span class="L_J lxr_order_pay" code="' + d.code + '" >立即支付</span>';
									html += '<span  class="lxr_order_cancel" code="' + d.code + '">取消订单</span>';
									break;
								case '1':
									html += '<span class="L_J">联系客服</span>';
									break;
								case '2':
									html += '<span class="L_J lxr_order_confirm" code="' + d.code + '" >确认收货</span>';
									break;
								case '3':
									html += '<span >马上评价</span>';
									break;
								case '4':
									html += '<span class="lxr_order_del" code="' + d.code + '" >删除订单</span>';
									break;
								case '5':
									html += '<span class="lxr_order_del" code="' + d.code + '">删除订单</span>';
									break;
							}
							html += '</p></li>';
						});
						$(".lxr_order_ShouHuo").append(html);
						$('.lxr_order_pay').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							viewApi.go("#tpl_OrderDetails",code);
						})
	
						$('.lxr_order_cancel').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.cancel_order, {
								code: code
							}, function(obj) {
								if(obj.s) {
									ShouHuo();
								}
							})
						})
						$('.lxr_order_del').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.del_order, {
								code: code
							}, function(obj) {
								if(obj.s) {
									ShouHuo();
								}
							})
						});
						$('.lxr_order_confirm').unbind('tap').on('tap',function() {
							var code = $(this).attr('code');
							Api.post(Api.confirm_good, {code: code},function(obj) {
								if(obj.s) {
									ShouHuo();
								}
							});
						});
					}
				}
			});
		}
	},
	LBT: function(swiper1,swiper2) {
		//轮播图
		var swiper = new Swiper(swiper1, {
			pagination: swiper2,
			paginationClickable: true,
			loop:true
		});
		swiper.update();
	},
	android_ios:function(){
		var android_ios = navigator.userAgent;
		var isAndroid = android_ios.indexOf('Android') > -1 || android_ios.indexOf('Adr') > -1; //android终端
		var isiOS = !!android_ios.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		androidIos = '';
		if(isAndroid == true){
			androidIos="android";
		}else if(isiOS == true){
			androidIos="ios";
		}
	},
	//
	showLoading:function(txt,fn){ 
		//$('#loading').fadeIn();
		if($('#loading').length>0) return false;
		$('body').append('<div id="loading"><div class="cc1"></div><div class="cc2"></div></div>');
	},
	closeLoading:function(fn){ 
		$('#loading').remove();
	},
	toeast: function(mes, time, fn) {
		var tm = time ? time : 2000;
		$('#alertmes>div').text(mes);
		$('#alertmes').fadeIn(function() {
			setTimeout(function() {
				$('#alertmes').fadeOut(function() {
					if(fn) fn();
				});
			}, tm);
		});
	},
	//打开窗口
	webview:function(){
		var parm = viewApi.parms;
		var url =fun.base64decode(parm[0]);
		var hbutton=$('.pHead').height();
		var styles={top:hbutton};
	    var id="webview_show";
		mui.plusReady(function() {
			var w =  plus.webview.create( url, id, styles );
			w.show(); // 显示窗口
			w.onloaded=function(){
				var title=w.getTitle();
				$('#webviewHeader h2').text(title);
			};
		});
		$(".icon-zuojiantou").show()
		fun.bindOnce(".icon-zuojiantou",'tap',function(){
			mui.plusReady(function() {
				plus.webview.close("webview_show");
				viewApi.back();
			});
		});
		(function(M){
			var oldBack = M.back;
			M.back = function() {
				mui.plusReady(function(){
					plus.webview.close("webview_show");
					viewApi.back();
				});
				return false;
			};
		})(mui);
	},
	//个推	
	gt:function(t,p,m,from){
		var type=t;
		var phone=p;
		var msg=m;
		var data={
			type:type,
			phone:phone,
			msg:msg,
			from:from
		}
		hx.post(hx.pushgt,data, function(obj){});
	},
	// 版本
	version:function(SetUp){
		var version="3.9.5";//当前版本
		var out=fun.getCache("version");
		if(out==false){
			fun.setCache("version",version);
		}else{
			if(out!=version){
				localStorage.clear();
			}
		}
		var android_ios = navigator.userAgent;
		var isAndroid = android_ios.indexOf('Android') > -1 || android_ios.indexOf('Adr') > -1; //android终端
		var isiOS = !!android_ios.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
		if(isAndroid == true){
			var system="android";
		}else if(isiOS == true){
			var system="ios"; return false;
		} 
		var data={
			system:system,
			version:version,
		};
		Api.post(Api.version,data,function(obj){
			var url=obj.d;
			if(obj.s){
				$('.rgba2').show();
				$('.update1').show();
				$('.update1 p').text(obj.m);
				fun.bindOnce('#UpDataDown','tap',function(){
					mui.plusReady(function(){
						plus.runtime.openURL(url,{},"");
					});
				})
				fun.bindOnce('#UpData','tap',function(){
					$('.rgba2').hide();
					$('.update1').hide();
				})
			}
			if(SetUp){
				if(obj.s == false){
					mui.toast('已经是最新版本');
				}
			}
		});
	},
	
	ios_window:function(bgd_color,color){
	   	if(mui.os.ios){
		   	mui.plusReady(function(){
			   	plus.navigator.setStatusBarBackground( bgd_color );
			   	plus.navigator.setStatusBarStyle( color );
		   	})
		}
	},
	// 美女直播
	tpl_BeautyLive:function(){
		$(".footer0").show();
		$(".footer li:nth-child(4) a p").css("color", "#ff5000");
		Api.post(Api.live_list,{},function(obj){
			if(obj.s){
				var html = '';
				$('.LiveList').empty();
				$.each(obj.d,function(i,d){
					html += '<li zid='+d.id+'><p><span>'+d.status+'</span><span>'+d.number+'</span></p><input zurl='+d.url+' readonly class="inputaaaaa" /><i style="background-image:url('+d.cover+')"></i><p>'+d.title+'</p></li>'
				});
				$('.LiveList').html(html);
				$('.LiveList li').unbind('tap').on('tap',function(){
					var url = $(this).find('.inputaaaaa').attr('zurl');
					var hbutton = $('.pHead').height();
					var styles = {top:hbutton};
				    var id="webview_show";
					mui.plusReady(function() {
						var w =  plus.webview.create( url, id, styles );
						w.show(); // 显示窗口
						w.onloaded=function(){
							var title=w.getTitle();
							$('#webviewHeader h2').text(title);
						};
					});
					$(".icon-zuojiantou").show()
					fun.bindOnce(".icon-zuojiantou",'tap',function(){
						mui.plusReady(function() {
							plus.webview.close("webview_show");
						});
					});
					(function(M){
						var oldBack = M.back;
						M.back = function() {
							mui.plusReady(function(){
								plus.webview.close("webview_show");
							});
							return false;
						};
					})(mui);
				});
			}
		})
	},
	// 维修工申请
	tpl_RepairApply:function(){
		$("#RepairApplyBtnsj").unbind('tap').on('tap',function(){
			var cityPicker3 = new mui.PopPicker({
				layer: 3
			});
			cityPicker3.setData(cityData3);
			cityPicker3.show(function(items) {
				var text = items[0].text + " " + items[1].text + " " + items[2].text;
				$('.address').val(text);
				$('.address').attr({'sheng':items[0].text,'shi':items[1].text,'qu':items[2].text});
				pageFun.getPlace(".address",items[0].text+items[1].text+items[2].text,items[0].text);
			});
		});
		
		pageFun.newupphoto('#Brand_UpImg2');
		$('#RepairApplyBtn').unbind('tap').on('tap',function(){
			var lng = $('#RepairApplyList .address').attr('lng');
			var lat = $('#RepairApplyList .address').attr('lat');
			var dom = $('#RepairApplyList');
			var name = dom.find('.name').val();
			var photo = dom.find('.photo').val();
			var sfzh = dom.find('.sfzh').val();
			var address = dom.find('.address').val();
			var sheng = dom.find('.address').attr('sheng');
			var shi = dom.find('.address').attr('shi');
			var qu = dom.find('.address').attr('qu');
			var jiedao = dom.find('.jiedao').val();
			var assessment = dom.find('.jies').val();
			var imgs = '';
			$.each($('.addimg .tu'),function(i,d){
				imgs += $(d).find('i').attr('src') + '@';
			});
			imgs = imgs.substr(0, imgs.length - 1);
			var Z_phone = /^1[0-9]{1}[0-9]{9}$/;
			var card2 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
			if(name && name != ''){
				if(photo && photo != ''){
					if(Z_phone.test(photo)){						
						if(sfzh && sfzh != ''){
							if(card2.test(sfzh)){								
								if(address && address != ''){
									if(jiedao && jiedao != ''){
										if(lng && lng != '' && lat && lat != ''){
											Api.post(Api.maintainer_apply,{name:name,mobile:photo,id_card:sfzh,lng:lng,lat:lat,province:sheng,assessment:assessment,city:shi,district:qu,address:jiedao,img:imgs},function(obj){
												if(obj.s){
													mui.toast('提交成功');
													viewApi.go('#tpl_My');
												}else{
													mui.toast(obj.m)
												}
											});
										}else{
											mui.toast('网络错误');
										}
									}else{
										mui.toast('请输入街道');
									}
								}else{
									mui.toast('详细地址不能为空');
								}
							}else{
								mui.toast('请输入正确的身份证号');
							}
						}else{
							mui.toast('身份证号不能为空');
						}
					}else{
						mui.toast('请输入正确的手机号')
					}
				}else{
					mui.toast('手机号码不能为空');
				}
			}else{
				mui.toast('姓名不能为空');
			}
		})
	},
	// 免费
	tpl_Admission:function(){
		var lng = fun.getCache('lng');
		var lat = fun.getCache('lat');
		var ace = fun.getCache('ace');
		$(".footer0").show();
		$(".footer li:nth-child(2) a p").css("color", "#ff5000");
		
		$('#AdmissionSS .icon-fangdajing').unbind('tap').on('tap',function(){
			var sta = $('#AdmissionNav .border-btm').attr('search_criteria');
			var val = $('#AdmissionSS input').val();
			var ds = $('#AdmissionQHBtn').attr('info');
			if(ds && ds != ''){
				ace = ds;
			}
			getdata(sta,val,lat,lng,ace);
		});
		$('#AdmissionNav li').unbind('tap').on('tap',function(){
			var sta = $('#AdmissionNav .border-btm').attr('search_criteria');
			var val = $('#AdmissionSS input').val();
			var ds = $('#AdmissionQHBtn').attr('info');
			if(ds && ds != ''){
				ace = ds;
			}
			getdata(sta,val,lat,lng,ace);
		});
		pageFun.sjld('#AdmissionQHBtn',function(){
			var sta = $('#AdmissionNav .border-btm').attr('search_criteria');
			var val = $('#AdmissionSS input').val();
			var ace = $('#AdmissionQHBtn').attr('info');
			getdata(sta,val,lat,lng,ace);
		});
		function getdata(type,key,lat,lng,ace){
			Api.post(Api.free_play_mj,{type:type,keyword:key,lng:lng,lat:lat,area:ace},function(obj){
				if(obj.s){
					var html = '';
					$.each(obj.d,function(i,d){
						html += '<li class="clearfix" zid="'+d.shop_id+'" num="0"><a href="#/tpl_shop/'+d.shop_id+'"><img src="'+d.listimg+'"><div><p class="shop_name NewShopName">'+d.shopname+'<span>免</span><span>'+d.free_date+'</span></p><p class="score" info="'+d.score+'">';
						for (var e = 0;e <= 4;e++){
							html +='<span class="iconfont icon-wujiaoxing"></span>';
						}
						html += '</p><p><span>'+d.area+'</span><span class="lxr_gps" lng="121.275104" lat="31.396709">'+d.distance+'</span></p></div></a></li>'
					});
					$('#AdmissionList').html(html);
					
					$.each($('#AdmissionList li'),function(i,d){
						var sta = $(d).find('.score').attr('info');
						$(d).find('.score span').slice(0,sta).css("color","#ff9d09");
					});
				}else{
					mui.toast(obj.m);
				};
			});
		}
		getdata(4,'',lat,lng,ace);
	},
	// 品牌详情
	tpl_DealerStore2:function(){
		
	},
	// 经销商店铺
	tpl_DealerStore:function(){
		
		var parm = viewApi.parms;
		
		function getdata(){
			Api.post(Api.nearby_shop_detail,{id:parm[0]},function(obj){
				if(obj.s){
					var obj = obj.d;
					var banner = '';
					var banner2 = '';
					$.each(obj.pictures, function(i,d) {
						banner += '<div class="mui-slider-item"><img src="'+d+'"></div>';
						banner2 += '<div class="mui-indicator"></div>';
					});
					$('#DealerStore .mui-slider-group').html(banner);
					$('#DealerStore .mui-slider-indicator').html(banner2);
					$('#DealerStore .mui-slider-indicator div').eq(0).addClass('mui-active');
					muiBanner();
					
					$('.titletext img').attr('src',obj.desc_img);
					
					var goods = '';
					$.each(obj.goods_list,function(i,d){
						goods += '<li zid="'+d.id+'"><i style="background-image:url('+d.picture+');"></i><p>'+d.goods_name+'</p><p>'+d.price+'</p></li>';
					});
					$('.List ul').html(goods);
					click();
				}else{
					mui.toast(obj.m)
				}
			})
		}
		getdata();
		
		function click(){
			$('.List ul li').unbind('tap').on('tap',function(){
				var id = $(this).attr('zid');
				viewApi.go('#tpl_nearby_shop_goods',[id,parm[0]]);
			})
		}
		
		function muiBanner(){
			var gallery = mui('#DealerStore');
			gallery.slider({
			  	interval:0
			});
		}
		
		$('.icon-zuojiantou').unbind('tap').on('tap',function(){
			viewApi.go('#home');
		});
		(function(M){
			var oldBack = M.back;
			M.back = function() {
				mui.plusReady(function(){
					viewApi.go('#home');
				});
				return false;
			};
		})(mui);
	},
	tpl_nearby_shop_goods:function(){
		var parm = viewApi.parms;
		
		$('#nearby_shop_goodsBtn').unbind('tap').on('tap',function(){
			$('.popQR').fadeIn(function(){
				popQR();
			});
		});
		
		function popQR(){
			$('.popQR').unbind('tap').on('tap',function(){
				$(this).fadeOut();
			})
		}
		
		$('.icon-zuojiantou').unbind('tap').on('tap',function(){
			viewApi.go('#tpl_DealerStore',[parm[1]]);
		});
		(function(M){
			var oldBack = M.back;
			M.back = function() {
				mui.plusReady(function(){
					viewApi.go('#tpl_DealerStore',[parm[1]]);
				});
				return false;
			};
		})(mui);
	},
	newupphoto:function(dom){
		$(dom).change(function() {
			var _this = this;
			var file = document.getElementById($(this).attr('id')).files[0];
			var fr = new FileReader();
			fr.onload = function(res) {
				$(_this).parents('li').before('<li class="tu"><i style="background-image: url('+res.target.result+');" src='+res.target.result+'></i><span class="remove">删除</span></li>');
				$(".remove").unbind('tap').on('tap',function() {
					var _this = $(this);
					$(this).parents('.tu').unbind();
					setTimeout(function(){
						_this.parents(".tu").remove();						
					},100);
				});
				$('.tu').unbind('tap').on('tap',function(){
					var src = $(this).find('i').attr('src');
					$('body').append('<div class="ImgCK"><img src="'+src+'"></div>');
					$('.ImgCK,.ImgCK img').unbind('tap').on('tap',function(){
						setTimeout(function(){
							$('.ImgCK').remove();
						},100)
					});
				});
			}
			fr.readAsDataURL(file);
		});
		
	},
	
	// 品牌入驻
	tpl_BrandSettled:function(){
		pageFun.newupphoto('#Brand_UpImg');
		
		$('#BrandSettledBtn').unbind('tap').on('tap',function(){
			var dom = $('.BrandSettledList');
			var name = dom.find('.name').val();
			var photo = dom.find('.photo').val();
			var address = dom.find('.address').val();
			var pinpainame = dom.find('.pinpainame').val();
			var pinpai = dom.find('.pinpai').val();
			var imgs = '';
			$.each($('.BrandSettled .addimg .tu'), function(i,d) {
				imgs += $(d).find('i').attr('src') + '@';
			});
			imgs = imgs.substr(0, imgs.length - 1);
			Api.post(Api.brand_apply,{name:name,mobile:photo,address:address,brand_name:pinpainame,brand_desc:pinpai,logo:imgs},function(obj){
				if(obj.s){
					
				}else{
					mui.toast(obj.m)
				}
			})
		});
	}
};

/*
*
* ━━━━━━神兽出没━━━━━━
*　　　　　　　　┏┓　　　┏┓+ +
*　　　　　　　┏┛┻━━━┛┻┓ + +
*　　　　　　　┃　　　　　　　┃ 　
*　　　　　　　┃　　　━　　　┃ ++ + + +
*　　　　　　 ████━████ ┃+
*　　　　　　　┃　　　　　　　┃ +
*　　　　　　　┃　　　┻　　　┃
*　　　　　　　┃　　　　　　　┃ + +
*　　　　　　　┗━┓　　　┏━┛
*　　　　　　　　　┃　　　┃　　　　　　　　　　　
*　　　　　　　　　┃　　　┃ + + + +
*　　　　　　　　　┃　　　┃　　　　Code is far away from bug with the animal protecting　　　　　　　
*　　　　　　　　　┃　　　┃ + 　　　　神兽保佑,代码无bug and 胖子越来胖　
*　　　　　　　　　┃　　　┃
*　　　　　　　　　┃　　　┃　　+　　　　　　　　　
*　　　　　　　　　┃　 　　┗━━━┓ + +
*　　　　　　　　　┃ 　　　　　　　┣┓
*　　　　　　　　　┃ 　　　　　　　┏┛
*　　　　　　　　　┗┓┓┏━┳┓┏┛ + + + +
*　　　　　　　　　　┃┫┫　┃┫┫
*　　　　　　　　　　┗┻┛　┗┻┛+ + + +
* ━━━━━━感觉萌萌哒━━━━━━
*/
